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 (useSortedDictionaryorOrderedDictionaryfor order). - Thread Safety: Modifying the dictionary while iterating will throw an
InvalidOperationException. UseConcurrentDictionaryfor thread-safe scenarios. - Performance: Iterating via
foreachis efficient (O(n) time complexity).
Summary
| Approach | Use Case | Example |
|---|---|---|
foreach with KeyValuePair | Iterate over all key-value pairs | foreach (var entry in myDict) { ... } |
Keys/Values properties | Iterate over keys or values only | foreach (string key in myDict.Keys) |
| LINQ | Filter, project, or transform entries | myDict.Where(...).Select(...) |
| Convert to List/Array | Store or process entries separately | myDict.ToList() |
This approach ensures efficient and clear iteration over dictionary entries in C#.