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

The idea is to create a sorted copy of the dictionary using LINQ’s OrderBy() method. For example, the following code iterates over a Dictionary in sorted order of keys using a foreach loop.

Download  Run Code

Output:

Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4

 
To sort in descending order, you can use the LINQ’s OrderByDescending() method, as shown below:

Download  Run Code

Output:

Key = D, Value = 4
Key = C, Value = 3
Key = B, Value = 2
Key = A, Value = 1

 
To iterate over the dictionary in sorted order of values, you can use the Value property of each KeyValuePair<K,V> pair. The following code example demonstrates this:

Download  Run Code

Output:

Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4

That’s all about iterating over a dictionary in sorted order in C#.