How to Iterate Over Dictionary in C# - Simple Guide
In C#, you can iterate over a dictionary using a
foreach loop on its KeyValuePair<TKey, TValue> elements. This lets you access both the key and value inside the loop easily.Syntax
Use a foreach loop to go through each KeyValuePair<TKey, TValue> in the dictionary. Inside the loop, you can access the Key and Value properties.
dictionary: your dictionary variablevar pair: each key-value pair in the dictionarypair.Key: the key of the current itempair.Value: the value of the current item
csharp
foreach (var pair in dictionary) { Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}"); }
Example
This example creates a dictionary of fruits and their colors, then iterates over it to print each fruit and its color.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { var fruits = new Dictionary<string, string> { {"Apple", "Red"}, {"Banana", "Yellow"}, {"Grape", "Purple"} }; foreach (var pair in fruits) { Console.WriteLine($"Fruit: {pair.Key}, Color: {pair.Value}"); } } }
Output
Fruit: Apple, Color: Red
Fruit: Banana, Color: Yellow
Fruit: Grape, Color: Purple
Common Pitfalls
One common mistake is trying to modify the dictionary (add or remove items) while iterating, which causes an error. Also, using foreach on just dictionary.Keys or dictionary.Values only gives keys or values, not both.
Always use KeyValuePair<TKey, TValue> to access both key and value together.
csharp
var dict = new Dictionary<int, string> { {1, "One"}, {2, "Two"} }; // Wrong: modifying dictionary during iteration // foreach (var pair in dict) // { // dict.Remove(pair.Key); // Throws InvalidOperationException // } // Correct way: collect keys first, then remove var keys = new List<int>(dict.Keys); foreach (var key in keys) { dict.Remove(key); }
Quick Reference
Here is a quick summary of how to iterate over a dictionary in C#:
| Action | Code Example |
|---|---|
| Iterate keys and values | foreach (var pair in dictionary) { var key = pair.Key; var value = pair.Value; } |
| Iterate keys only | foreach (var key in dictionary.Keys) { } |
| Iterate values only | foreach (var value in dictionary.Values) { } |
| Avoid modifying during iteration | Collect keys first, then modify outside loop |
Key Takeaways
Use foreach with KeyValuePair to access both keys and values in a dictionary.
Do not modify the dictionary while iterating over it to avoid runtime errors.
You can iterate keys or values separately using dictionary.Keys or dictionary.Values.
Collect keys first if you need to remove items during iteration.