Logo

How to iterate over a dictionary in C#?

Iterating over a Dictionary<TKey, TValue> in C# is essential for scenarios like collecting data insights, transforming key-value pairs, or debugging. Below, you’ll find several methods to iterate through a dictionary along with best practices and tips.

Using foreach with KeyValuePair

A straightforward approach to iterate through every key-value pair:

var dictionary = new Dictionary<int, string>() { {1, "One"}, {2, "Two"}, {3, "Three"} }; foreach (KeyValuePair<int, string> kvp in dictionary) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); }
  • How it Works: This loop unpacks each key-value pair into a KeyValuePair<TKey, TValue> structure, allowing direct access to Key and Value.

Iterating over Keys Only

If you only need to process or display dictionary keys:

foreach (int key in dictionary.Keys) { Console.WriteLine($"Key: {key}"); }
  • Why Use This: Sometimes you only need the keys—for instance, when checking if a certain key exists or for creating a subset of the dictionary.

Iterating over Values Only

If you only require the values:

foreach (string value in dictionary.Values) { Console.WriteLine($"Value: {value}"); }
  • Use Case: Working with the values to perform aggregations or transformations without needing the keys.

Using LINQ

Another common technique involves using LINQ to project or filter key-value pairs. For example:

var filtered = dictionary .Where(kvp => kvp.Key > 1) .Select(kvp => kvp.Value); foreach (var val in filtered) { Console.WriteLine(val); }
  • Why LINQ: LINQ makes it easy to chain conditions, map to new structures, and keep your code concise.

Best Practices

  1. Check for Null: Ensure your dictionary is not null before iterating to avoid runtime exceptions.
  2. Avoid Modifications While Iterating: Adding or removing entries within a loop can throw an InvalidOperationException.
  3. Use TryGetValue: Instead of checking ContainsKey, prefer dictionary.TryGetValue(key, out value) for thread-safe scenarios and improved performance.

Strengthen Your C# Skills

If you’re aiming to sharpen your coding fundamentals and ace technical interviews, consider expanding your knowledge with courses that focus on pattern-based learning and advanced problem-solving:

These resources offer structured practice in tackling complex coding challenges and refining your understanding of C# and .NET best practices.

Whether you’re iterating over a dictionary for quick lookups, performing data transformations, or preparing for an interview, understanding these iteration techniques will keep your code clean, efficient, and easy to maintain. For more insights, tips, and in-depth tutorials on coding and system design, subscribe to DesignGurus.io’s YouTube channel.

CONTRIBUTOR
TechGrind