C# - Iterate over a Dictionary

C# - Iterate over a Dictionary

c#, c# iterate dictionary, c# loop through dictionary, Dictionary, foreach, iterate

This tutorial will explain how to iterate a dictionary in C#. But before learning to loop a dictionary we will first learn to initialize a dictionary. We also touch on using LINQ to manipulate key value pairs. 

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. Also remember the using reference when using the dictionary class collection initializer. 

using system.collections.generic;
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. The collection of keys is looped until there no keys left to read. Check out the C# dictionary example below:

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.

exampleDictionary.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!



Back to The Programmer Blog