在 C# 中对元组列表进行排序 [英] Sort tuple list in C#
本文介绍了在 C# 中对元组列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C#.NET 上工作.我有这个清单:
Working on C#.NET. I have this list:
List<Tuple<string, float>> sort = new List<Tuple<string, float>>();
我想按浮点值对这个列表进行排序.例如,如果列表是这样的:
I want to sort this list by the float value. Eg if the list is like this:
a,45
b,2
s,32
se,83.21
te,84
s3,9.5
f,7
我希望它按降序排序,如下所示:
I want it to be sorted in a descending order, like this:
te,84
se,83.21
a,45
s,32
s3,9.5
f,7
b,2
推荐答案
如果要对列表进行就地排序,可以使用 Sort
方法采用 Comparison
参数.
If you want to sort the list inplace, you can use the Sort
method that takes Comparison<T>
argument.
要按Tuple.Item2
升序排序,可以使用
To sort by the Tuple.Item2
in ascending order, you can use
sort.Sort((a, b) => a.Item2.CompareTo(b.Item2));
要降序排序,只需交换a
和b
:
To sort in descending order, just swap a
and b
:
sort.Sort((a, b) => b.Item2.CompareTo(a.Item2));
这篇关于在 C# 中对元组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文