Dictionaries in C#: Why They Matter and How to Work with Them?
Imagine you are a librarian. You have thousands of books, and you need to find a specific one in a second. Would you go through all the books one by one? No, you would use a catalog. Dictionary in C# is exactly that kind of catalog. It stores key-value pairs and allows you to instantly retrieve data by key.
But what do you do when you need not to find a single entry, but to process all the contents of the dictionary? For example, output all application settings, calculate the total in an online store cart, or serialize data to JSON. This is where the classic question arises: "How to iterate over a dictionary?".
On Stack Overflow, this question has garnered thousands of views. And for good reason: it seems simple, right? But beginners often stumble on data types, and pros on performance. In this article, we will cover all ways to iterate over a dictionary in C#: from simple foreach to advanced LINQ. Let's go!
1. The Basics: Dictionary Structure in C#
Before iterating, let's recall what a C# dictionary looks like. It is a generic collection from the System.Collections.Generic namespace.
Dictionary<string, int> ages = new Dictionary<string, int>(){ { "Anna", 25 }, { "Boris", 30 }, { "Victor", 35 }};Each element of the dictionary is a KeyValuePair<TKey, TValue> structure. It has two properties: Key and Value. It is this pair that we will work with during traversal.
2. The Classic: foreach over a Dictionary
The most common way to iterate over a dictionary in C# is the foreach loop. It is concise, readable, and safe.
foreach (KeyValuePair<string, int> kvp in ages){ Console.WriteLine($"{kvp.Key}: {kvp.Value} years old");}Output:
Anna: 25 years oldBoris: 30 years oldVictor: 35 years oldNote: kvp is a KeyValuePair. Do not try to modify the key or value inside the loop — the dictionary will become inconsistent, and you will get an InvalidOperationException.
Pro tip: If you are too lazy to write the full type, use var:
foreach (var kvp in ages) { ... }3. Only Keys or Only Values
Sometimes we don't need the whole pair. For example, we just need to output a list of all keys (names) or all values (ages). For this, the dictionary has Keys and Values properties.
Iterating over Keys
foreach (string name in ages.Keys){ Console.WriteLine($"Name: {name}");}Iterating over Values
foreach (int age in ages.Values){ Console.WriteLine($"Age: {age}");}This is faster than getting a KeyValuePair if you don't need the other part. Plus, the code becomes cleaner.
4. Index Access: for and ElementAt
Many beginners try to use for (int i = 0; i < dict.Count; i++). But Dictionary in C# does not support an indexer by number! Trying to write dict[i] will cause a compilation error.
However, you can work around it: get a collection of pairs via .ToList() and access by index.
var list = ages.ToList();for (int i = 0; i < list.Count; i++){ Console.WriteLine($"{list[i].Key}: {list[i].Value}");}Cons:
- Creates an additional copy of the data (memory + time).
- Loses the point of the dictionary as an associative array.
This method should only be used if you absolutely need an index (e.g., for parallel processing with partitioning).