This post will discuss how to iterate over a dictionary in C#.

1. Using foreach Loop

We can loop through all KeyValuePair<K,V> in the dictionary and print the corresponding Key and Value from each pair.

Download  Run Code

 
We can also iterate over the collection of keys and fetch the value using the Item[TKey] property.

Download  Run Code

 
Starting with C# 7.0, multiple fields can be retrieved from an object in a single deconstruct operation by assigning selected values to individual variables. The following example uses type inference when deconstructing inside the foreach loop, which lets us unpackage key and value in KeyValuePair<K,V> in a single operation.

Download  Run Code

 
We can also explicitly declare the type of each field inside the parentheses, as shown below:

Download  Run Code

2. Using for loop

We can also use a for-loop to iterate over a directory. To get KeyValuePair<K,V> at a specified index in a sequence, use ElementAt() method.

Download  Run Code

3. Using ParallelEnumerable.ForAll() method

A simple and fairly efficient solution to iterate over large dictionaries is using the ParallelEnumerable.ForAll() method. This method is demonstrated below:

Download  Run Code

4. Using String.Join() method

Finally, the String.Join() method can be used to print all KeyValuePair<K,V> in dictionary separated by a delimiter.

Download  Run Code

That’s all about iterating over a Dictionary in C#.