Iterate over a Dictionary in sorted order in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"B", 2}, {"A", 1}, {"D", 4}, {"C", 3} }; foreach (var kvp in dict.OrderBy(x => x.Key)) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"B", 2}, {"A", 1}, {"D", 4}, {"C", 3} }; foreach (var kvp in dict.OrderByDescending(x => x.Key)) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"B", 2}, {"A", 1}, {"D", 4}, {"C", 3} }; foreach (var kvp in dict.OrderBy(x => x.Value)) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } } |
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#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)