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:
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>() {
{"A", 15}, {"B", 10}, {"C", 12}, {"D", 20}, {"E", 14}
};
var sortedDict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
Console.WriteLine(String.Join(", ", sortedDict));
}
}
|
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.
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>() {
{"A", 15}, {"B", 10}, {"C", 12}, {"D", 20}, {"E", 14}
};
var sortedDict = from item in dict orderby item.Value ascending select item;
Console.WriteLine(String.Join(", ", sortedDict));
}
}
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
Dictionary<string, int> dict = new Dictionary<string, int>() {
{"A", 15}, {"B", 10}, {"C", 12}, {"D", 20}, {"E", 14}
};
List<KeyValuePair<string, int>> mappings = dict.ToList();
mappings.Sort((x, y) => x.Value.CompareTo(y.Value));
Console.WriteLine(String.Join(", ", mappings));
}
}
|
Output:
[B, 10], [C, 12], [E, 14], [A, 15], [D, 20]
The above code can be shortened to 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>() {
{"A", 15}, {"B", 10}, {"C", 12}, {"D", 20}, {"E", 14}
};
List<KeyValuePair<string, int>> mappings = dict.OrderBy(d => d.Value).ToList();
Console.WriteLine(String.Join(", ", mappings));
}
}
|
Output:
[B, 10], [C, 12], [E, 14], [A, 15], [D, 20]
That’s all about sorting a dictionary by value in C#.