C# – Loop through a dictionary

The simplest way to loop through a dictionary is with a foreach loop. Here’s an example of initializing a dictionary with values and then looping through it:

var dictionary = new Dictionary<string, int>()
{
    ["cat"] = 1,
    ["dog"] = 3,
    ["fish"] = 10
};

foreach(var kvp in dictionary)
{
    var word = kvp.Key;
    var count = kvp.Value;

    Console.WriteLine($"{word} appeared {count} time(s)");
}
Code language: C# (cs)

This outputs the following:

cat appeared 1 time(s)
dog appeared 3 time(s)
fish appeared 10 time(sCode language: plaintext (plaintext)

The loop variable is a KeyValuePair<string, int> with Key and Value properties. Instead of using this, you can deconstruct the KeyValuePair into named variables, like this:

foreach(var (word, count) in dictionary)
{
    Console.WriteLine($"{word} appeared {count} time(s)");
}
Code language: C# (cs)

This simplifies things and makes the loop easier to read.

Don’t use a for loop

Dictionaries are unordered. It doesn’t make sense to loop over them with a for loop + ElementAt(). This approach is incredibly inefficient. Internally, ElementAt() loops over the dictionary to find the Nth element. In other words, it’s a nested loop with a time complexity of O(n ^ 2).

The problem you’re probably trying to solve is getting the “index” to display to the user. What you really want is a sorted dictionary + the sort positions. See the section above for examples of looping over sorted dictionaries. This has a time complexity of O(n log n), which is an order of magnitude better than the for loop + ElementAt() approach.

Leave a Comment