如何按降序对通用排序列表?
本文关键字:排序 列表 何按 降序 | 更新日期: 2023-09-18 11:28:00
你已在 C# 教程部分中了解了SortedList<TKey, TValue>。默认情况下,SortedList
SortedList
class DecendingComparer<TKey>: IComparer<int>
{
public int Compare(int x, int y)
{
return y.CompareTo(x);
}
}
class Program
{
static void Main(string[] args)
{
SortedList<int, int> descSortedList = new SortedList<int, int>(new DecendingComparer<int>());
descSortedList.Add(1, 1);
descSortedList.Add(4, 4);
descSortedList.Add(3, 3);
descSortedList.Add(2, 2);
for (int i = 0; i < descSortedList.Count; i++)
{
Console.WriteLine("key: {0}, value: {1}", descSortedList.Keys[i], descSortedList.Values[i]);
}
}
使用 Comparer
class Program
{
static void Main(string[] args)
{
var descendingComparer = Comparer<int>.Create((x, y) => y.CompareTo(x));
SortedList<int, int> descSortedList = new SortedList<int, int>(descendingComparer);
descSortedList.Add(1, 1);
descSortedList.Add(4, 4);
descSortedList.Add(3, 3);
descSortedList.Add(2, 2);
for (int i = 0; i < descSortedList.Count; i++)
{
Console.WriteLine("key: {0}, value: {1}", descSortedList.Keys[i], descSortedList.Values[i]);
}
}
因此,您可以创建 SortedList