0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ with Dictionary in C# - Simple Guide

You can use LINQ with a Dictionary<TKey, TValue> by querying its KeyValuePair elements using methods like Where, Select, and OrderBy. LINQ lets you filter or transform dictionary entries by accessing their Key and Value properties in the query.
📐

Syntax

LINQ queries on a dictionary work with KeyValuePair<TKey, TValue> objects. You can use query syntax or method syntax to filter or select data.

  • dictionary.Where(kv => condition): Filters entries based on a condition.
  • dictionary.Select(kv => projection): Projects each entry into a new form.
  • kv.Key: Accesses the key of the dictionary entry.
  • kv.Value: Accesses the value of the dictionary entry.
csharp
var filtered = dictionary.Where(kv => kv.Value > 10);
var keys = dictionary.Select(kv => kv.Key);
var sorted = dictionary.OrderBy(kv => kv.Value);
💻

Example

This example shows how to use LINQ to filter a dictionary for values greater than 50, then select and print the matching keys and values.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var scores = new Dictionary<string, int>
        {
            {"Alice", 75},
            {"Bob", 45},
            {"Charlie", 90},
            {"Diana", 30}
        };

        var highScores = scores.Where(kv => kv.Value > 50);

        foreach (var kv in highScores)
        {
            Console.WriteLine($"{kv.Key}: {kv.Value}");
        }
    }
}
Output
Alice: 75 Charlie: 90
⚠️

Common Pitfalls

Common mistakes when using LINQ with dictionaries include:

  • Trying to query dictionary keys or values directly without accessing KeyValuePair elements.
  • Assuming LINQ returns a dictionary; it returns IEnumerable<KeyValuePair<TKey, TValue>> unless you convert it.
  • Modifying the dictionary while enumerating it causes errors.

Always remember to use ToDictionary() if you want the result as a dictionary.

csharp
var filtered = scores.Where(kv => kv.Value > 50);
// filtered is IEnumerable<KeyValuePair<string, int>>, not Dictionary

// To get a dictionary:
var filteredDict = filtered.ToDictionary(kv => kv.Key, kv => kv.Value);
📊

Quick Reference

Use these LINQ methods with dictionaries:

LINQ MethodDescriptionExample Usage
WhereFilters entries by conditiondictionary.Where(kv => kv.Value > 10)
SelectProjects entries to new formdictionary.Select(kv => kv.Key)
OrderBySorts entries by key or valuedictionary.OrderBy(kv => kv.Value)
ToDictionaryConverts IEnumerable back to Dictionaryfiltered.ToDictionary(kv => kv.Key, kv => kv.Value)

Key Takeaways

LINQ queries on dictionaries work with KeyValuePair elements using Key and Value properties.
Use Where, Select, and OrderBy to filter, transform, and sort dictionary entries.
LINQ returns IEnumerable, use ToDictionary() to convert back to a dictionary.
Avoid modifying a dictionary while enumerating it with LINQ to prevent runtime errors.
Access keys and values inside the lambda expressions to write effective LINQ queries.