When you loop through a dictionary, whether it’s with a foreach or with a Linq method, you’ll be dealing with KeyValuePair objects, which have Key and Value properties (same types as the dictionary).
Here’s an example of how to loop through a dictionary with a foreach:
var wordCountMap = new Dictionary<string, int>()
{
["cat"] = 1,
["dog"] = 3,
["fish"] = 10
};
foreach(var kvp in wordCountMap)
{
var word = kvp.Key;
var count = kvp.Value;
Console.WriteLine($"{word} appeared {count} time(s)");
}
Code language: C# (cs)
Note: The loop variable (kvp) is a KeyValuePair<string, int> – same key/value type as the dictionary. It’s way less verbose to use ‘var’, and it’s common to use ‘kvp’ as the name.
This outputs the following:
Code language: plaintext (plaintext)cat appeared 1 time(s) dog appeared 3 time(s) fish appeared 10 time(s
Here’s an example of using the Linq Where() method to filter a dictionary and loop over its filtered key/value pairs:
using System.Linq;
foreach(var longWordKVP in wordCountMap.Where(kvp => kvp.Key.Length > 3))
{
Console.WriteLine($"Long word '{longWordKVP.Key}' appeared {longWordKVP.Value} times");
}
Code language: C# (cs)
This outputs the following:
Code language: plaintext (plaintext)Long word 'fish' appeared 10 times
Besides looping through a dictionary’s key/value pairs, you can also loop through just the keys or just the values. I’ll show examples below.
Table of Contents
Loop through the keys
Here’s an example of looping through a dictionary’s keys:
var coderCounts = new Dictionary<string, int>()
{
["C#"] = 12,
["Java"] = 10,
["C++"] = 2,
};
Console.WriteLine("We have coders that use the following languages:");
foreach (var lang in coderCounts.Keys)
{
Console.WriteLine(lang);
}
Code language: C# (cs)
This outputs the following:
Code language: plaintext (plaintext)We have coders that use the following languages: C# Java C++
Here’s an example of using Linq to simplify filtering a dictionary’s keys:
using System.Linq;
var langs = coderCounts.Keys.Where(lang => lang.StartsWith("C"));
Console.WriteLine($"We have {langs.Count()} language(s) that start with 'C'");
Code language: C# (cs)
This outputs:
Code language: plaintext (plaintext)We have 2 language(s) that start with 'C'
Loop through the values
Here’s an example of looping through a dictionary’s values:
var wordCountMap = new Dictionary<string, int>()
{
["cat"] = 10,
["dog"] = 30,
["fish"] = 2
};
foreach (var count in wordCountMap.Values)
{
Console.WriteLine(count);
}
Code language: C# (cs)
This outputs the following:
Code language: plaintext (plaintext)1 3 10
Here’s an example of using Linq to simplify finding the max value in the dictionary:
using System.Linq;
var maxCount = wordCountMap.Values.Max();
Console.WriteLine($"Max count is {maxCount}");
Code language: C# (cs)
This outputs the following:
Code language: plaintext (plaintext)Max count is 10
Sorted order
Key/value pairs aren’t returned in any particular order when you loop through a dictionary. If you need them in sorted order, the simplest way is to use the Linq OrderBy() method.
For example, let’s say you want you to loop through the dictionary with the keys in alphabetical order:
using System.Linq;
var wordCountMap = new Dictionary<string, int>()
{
["boy"] = 1,
["zebra"] = 3,
["apple"] = 10
};
Console.WriteLine("The word counts in alphabetical order:");
foreach(var kvp in wordCountMap.OrderBy(kvp => kvp.Key))
{
Console.WriteLine($"{kvp.Key}={kvp.Value}");
}
Code language: C# (cs)
This outputs the following:
Code language: plaintext (plaintext)The word counts in alphabetical order: apple=10 boy=1 zebra=3