Sort a Dictionary by value in C#

原文地址:Sort a Dictionary by value in C#

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]

 
This works since a Dictionary<TKey,TValue> 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

Alternatively, 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#.

posted on 2022-07-26 15:53  ZhYQ_note  阅读(47)  评论(0)    收藏  举报

导航