C# - Iterate over a Dictionary

C# - Iterate over a Dictionary

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 a Dictionary

Init a sample dictionary 

Dictionary exampleDictionary = new Dictionary
        {
            { "key1", "value1" },
            { "key2", "value2" }
        };

Iterating the Dictionary

Iterate the dictionary using a foreach statement. Ex. On the first iteration kv.Value would equal "Value1".

foreach(KeyValuePair kv in exampleDictionary)
{
    // do something with kv.Value or kv.Key
}

Using a generic or custom Dictionary

Iterate a dictionary of generic or custom object is pretty much the same as above, with the caveat that you must cast each item and use the property name.

foreach(var obj in genericDictionary)
{
  // do something with obj.Key or obj.Value or obj.Value.YourProp
}

Iterating only keys

Here's a simple example if you only need the keys.

foreach(var key in genericDictionary.Keys)
{
  // do something with key
}

Iterating only values

Quick foreach to iterate the Dictionary values

foreach(var value in genericDictionary.Values)
{
  // do something with value
}

LINQ

Using a ForEach LINQ statement to iterate a dictionary. 

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

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.

genericDictionary.AsParallel()
.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.

Cheers!