This post will discuss how to sort a dictionary by value in C#.

1. Using OrderBy() Method

The idea is to sort the dictionary by value using the OrderBy() method. Then, you can collect each key-value pair in the sorted collection and create a new dictionary using the LINQ’s ToDictionary() method. Note that this works with .NET framework 3.5 and above and requires System.Linq namespace. The complete code is shown below:

Download  Run Code

Output:

[B, 10], [C, 12], [E, 14], [A, 15], [D, 20]

 
Note that a Dictionary is not ordered by definition. The above code works, but it is implementation dependent and is not guaranteed to always work. To guarantee KeyValuePair will stay in the desired order, you should construct a list from the sorted items.

 
The OrderBy() method works with a Dictionary<TKey,TValue> since it already implements IEnumerable. The following code uses LINQ query syntax to achieve the same without using the ToDictionary() method.

Download  Run Code

Output:

[B, 10], [C, 12], [E, 14], [A, 15], [D, 20]

2. Using a List

You can save a sorted copy of the Dictionary as a List. The following code demonstrates this using the ToList() method.

Download  Run Code

Output:

[B, 10], [C, 12], [E, 14], [A, 15], [D, 20]

 
The above code can be shortened to below.

Download  Run Code

Output:

[B, 10], [C, 12], [E, 14], [A, 15], [D, 20]

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