Different Ways to Iterate Dictionary in C#

Dictionary in C# is a collection of Key value pair under the System.Collections.Generic namespace. Dictionary is optimized for fetching and saving values with constant complexity- O(1)
Let us quickly look at ways to iterate over a dictionary.

Consider below dictionary

    Dictionary<string, int> wordFrequency 
                        = new Dictionary<string, int>();
    wordFrequency.Add("A", 1);
    wordFrequency.Add("B", 2);
    wordFrequency.Add("C", 3);
    wordFrequency.Add("D", 4);

Iterate Dictionary using Foreach loop

    int max = 0;
    foreach(var v in wordFrequency)
    {
       if (v.Value > max)
       {
           max = v.Value;
       }
    }

Iterate Dictionary using ForEach Lambda

We can dictionary using System.Collections.Generic ForEach Method and LINQ ToList Method as below

    int max = 0;
    wordFrequency.ToList().ForEach(x=> {
       if (x.Value > max)
       {
          max = x.Value;
       }
    });

We use the LINQ’s ToList method to convert the dictionary into List type. List Contains the ForEach Method which takes a lambda to iterate over the list.

Iterate Dictionary with Index

We can iterate dictionary using index by converting the dictionary into another object. But remember to not rely on this for ordering purposes since the indexing is being done after the dictionary is created. So it can be used for rendering purposes. If Indexing is mandatory in your implementation, then you may need to reconsider the data structure.

    var indexedWordFrequency = 
               wordFrequency.Select((Object, i) => new { Object, i });
    
    foreach (var v in indexedWordFrequency)
    {
       Console.WriteLine("index = " + v.i);
       Console.WriteLine("Object = Key = " + 
                         v.Object.Key + " Value = " +
                         v.Object.Value);
    }

Since above implementation is not reliable for exact ordering, we may create dictionary in below format.

    Dictionary<int, KeyValuePair<string, int>> wordFrequency = 
                  new Dictionary<int, KeyValuePair<string, int>>();

    wordFrequency.Add(1, new KeyValuePair<string, int>("A",1));
    wordFrequency.Add(2, new KeyValuePair<string, int>("B",2));
    wordFrequency.Add(3, new KeyValuePair<string, int>("C",3));

    int max = 0; int index = 0;
    wordFrequency.ToList().ForEach(x =>
    {
       if (x.Value.Value > max)
       {
          max = x.Value.Value;
          index = x.Key;
       }
    });
   
    Console.WriteLine(max);

Iterating with parallel processing

We can do iteration for parallel processing using the AsParallel Method of the System.Linq library.

    wordFrequency.AsParallel().ForAll(x=> {
        Console.WriteLine(x.Value);
    });

Since it is parallel processing we need to ensure that the processing is not dependent on each other.

Iterate Dictionary and Change Values

We use LINQ to get list of all keys and iterate over the keys

    foreach (var v in wordFrequency.Keys.ToList())
    {
       wordFrequency[v]++;
    }

Using Deconstructors in C# 7.0

After .NET 2.0, inbuilt Deconstructor is introduced in various classes to separate out the original properties from a class, i.e. deconstruct the class. Deconstruct method is provided in KeyValuePair class which is being used in the dictionary.

We can use this using the below syntax to deconstruct our dictionary to iterate over the dictionary

    foreach (var (k, v) in wordFrequency)
    {
        Console.WriteLine("key = " + k + " value = " + v);
    }

Conclusion

So we have looked at various ways to iterate over a dictionary. If you have any suggestions, please do mention in the comment box.

Leave a Comment

Your email address will not be published.