在C#中对KeyValuePairs进行排序
使用Sort方法对KeyValuePairs集合进行排序。
首先,设置集合-
var myList = new List<KeyValuePair<int, int>>(); //添加元素 myList.Add(new KeyValuePair<int, int>(1, 20)); myList.Add(new KeyValuePair<int, int>(2, 15)); myList.Add(new KeyValuePair<int, int>(3, 35)); myList.Add(new KeyValuePair<int, int>(4, 50)); myList.Add(new KeyValuePair<int, int>(5, 25));
要排序,请使用Sort()方法。至此,我们已经使用该CompareTo()方法比较值-
myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));
以下是完整的代码-
示例
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var myList = new List<KeyValuePair<int, int>>();
//添加元素
myList.Add(new KeyValuePair<int, int>(1, 20));
myList.Add(new KeyValuePair<int, int>(2, 15));
myList.Add(new KeyValuePair<int, int>(3, 35));
myList.Add(new KeyValuePair<int, int>(4, 50));
myList.Add(new KeyValuePair<int, int>(5, 25));
Console.WriteLine("Unsorted List...");
foreach (var val in myList) {
Console.WriteLine(val);
}
//排序值
myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));
Console.WriteLine("Sorted List...");
foreach (var val in myList) {
Console.WriteLine(val);
}
}
}输出结果
Unsorted List... [1, 20] [2, 15] [3, 35] [4, 50] [5, 25] Sorted List... [4, 50] [3, 35] [5, 25] [1, 20] [2, 15]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下