C# - Iterate over a Dictionary

C# - Iterate over a Dictionary

c#, Dictionary, foreach, iterate

In the world of C# programming it's common to trip over something as easy as iterating over a dictionary. We've put together a quick reference guide below to give you a quick intro or refresher into manipulating dictionaries in C#.

Initializing an example Dictionary

So first let's initialize a sample dictionary, named exampleDictionary. We will populate it with two key value pairs as shown below.

Dictionary<string,string> exampleDictionary = new Dictionary<string,string>
{ "key1", "value1" },
{ "key2", "value2" }

Iterating the Dictionary

In C# Iterating a dictionary is typically done using a foreach statement. This loop each KeyValuePair within the Dictionary. Below is an example of iterating the exampleDictionary to read the values KeyValuePair.

foreach(KeyValuePair kv in exampleDictionary)
    // do something with kv.Value or kv.Key
    // Results of first iteration:
    // kv.Key = "key1" 
    // kv.Value = "value1" 

// Iterating only keys
foreach(var key in exampleDictionary.Keys) { // do something with key }

// Iterating only values
foreach(var val in exampleDictionary.Values) { // do something with val }

C# Iterate a Dictionary using LINQ

The other common method used to iterate a Dictionary in C# is good ol' LINQ. In this example we are first doing a .ToList(), followed by a .ForEach(). This will give us each KeyValuePair.

exampleDictionary.ToList().ForEach(kv =>
  // do something with kv.Key or kv.Value
// if custom object, kv.Value.YourProp });

// Iterating only keys exampleDictionary.Select(kv => kv.Key).ToList().ForEach(k=> { // do something with k });

// Iterating only values exampleDictionary.Select(kv => kv.Value).ToList().ForEach(v => { // do something with v });

C# Iterate a Dictionary using Multi-threaded LINQ

* This should be used with caution as it can cause serious performance implications if abused. An appropriate use case may be a scenario where you are processing large amounts of data with each item in the dictionary. If you use this method, ensure that the items do not depend on each other.

.ForAll(kv => 
    // do something with kv.Key or kv.Value
// if custom object, kv.YourProp });

Hopefully this helped out! If you would like to dive deeper into the Dictionary in C# I would definitely recommend checking out the MSDN Dictionary<T,T>.

Keep tuned for more quick reference guides similar to this.