Sort Dictionary by keys in C#
This post will discuss how to sort a dictionary by its keys in C#.
1. Using SortedDictionary<TKey,TValue>
You can’t sort a Dictionary<TKey,TValue>
since it is implemented as a hash table. You can use SortedDictionary<TKey,TValue>
instead, which represents a dictionary where key/value pairs are sorted on the key, and it is implemented as a binary search tree with logarithmic time retrieval operation.
The idea is to pass the regular dictionary to the SortedDictionary
constructor, which will then initializes a new instance of the dictionary, containing the same mappings as the specified dictionary, but ordered according to the keys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Collections.Generic; public static class Extensions { public static SortedDictionary<TKey, TValue> SortByKey<TKey, TValue>( this IDictionary<TKey, TValue> dict) { return new SortedDictionary<TKey, TValue>(dict); } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; var sortedDict = dict.SortByKey(); Console.WriteLine(String.Join(", ", sortedDict)); // [A, 1], [B, 2], [C, 3] } } |
2. Using Sorting
Alternatively, you can get a collection of keys present in the dictionary and sort it. Then, you can process each key-value pair for every key in the sorted collection. Note that this requires LINQ and you need to add System.Linq
namespace.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static void processInSortedOrder<TKey, TValue>(this IDictionary<TKey, TValue> dict) { foreach (var key in dict.Keys.OrderBy(x => x)) { Console.WriteLine("{0}: {1}", key, dict[key]); } } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; dict.processInSortedOrder(); } } |
That’s all about sorting a dictionary by its keys 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 :)