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.

Download  Run Code

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.

Download  Run Code

That’s all about sorting a dictionary by its keys in C#.