How to iterate over a dictionary in C#?

To iterate over a dictionary in C#, you can use a foreach loop to access each key-value pair. Here’s a step-by-step explanation with examples:

1. Basic Iteration Using foreach

Loop through all entries in the dictionary as KeyValuePair<TKey, TValue>:

Dictionary<string, int> myDict = new Dictionary<string, int>
{
    { "Apple", 10 },
    { "Banana", 5 },
    { "Cherry", 8 }
};

foreach (KeyValuePair<string, int> entry in myDict)
{
    Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}

Output:

Key: Apple, Value: 10
Key: Banana, Value: 5
Key: Cherry, Value: 8

2. Using var for Simplicity

Let the compiler infer the type of KeyValuePair:

foreach (var entry in myDict)
{
    Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}

3. Iterate Over Keys or Values Only

Loop Through Keys:

foreach (string key in myDict.Keys)
{
    Console.WriteLine($"Key: {key}");
}

Loop Through Values:

foreach (int value in myDict.Values)
{
    Console.WriteLine($"Value: {value}");
}

4. Using LINQ for Filtering/Projection

Process entries with LINQ methods like Where or Select:

// Filter entries where the value is greater than 5
foreach (var entry in myDict.Where(kvp => kvp.Value > 5))
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

Output:

Apple: 10
Cherry: 8

5. Convert to List or Array

Convert the dictionary to a list of key-value pairs for further processing:

List<KeyValuePair<string, int>> entries = myDict.ToList();

Key Notes

  • Order Not Guaranteed: Standard Dictionary<TKey, TValue> does not preserve insertion order (use SortedDictionary or OrderedDictionary for order).
  • Thread Safety: Modifying the dictionary while iterating will throw an InvalidOperationException. Use ConcurrentDictionary for thread-safe scenarios.
  • Performance: Iterating via foreach is efficient (O(n) time complexity).

Summary

ApproachUse CaseExample
foreach with KeyValuePairIterate over all key-value pairsforeach (var entry in myDict) { ... }
Keys/Values propertiesIterate over keys or values onlyforeach (string key in myDict.Keys)
LINQFilter, project, or transform entriesmyDict.Where(...).Select(...)
Convert to List/ArrayStore or process entries separatelymyDict.ToList()

This approach ensures efficient and clear iteration over dictionary entries in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *