如何对一个 List<Tuple<int, double>> 进行排序?

7
你好,感谢阅读这篇文章。
我有一个用以下方式创建的列表。
List<Tuple<int, double>> Ratings = new List<Tuple<int, double>>();

假设列表的值如下:
Index      int     double

[0]        1       4,5
[1]        4       1,0
[2]        3       5,0
[3]        2       2,5

如何对列表进行排序,使最高的双倍值排在最上面?就像这样:
Index      int     double
[0]        3       5,0
[1]        1       4,5
[2]        2       2,5
[3]        4       1,0

1
Ratings = Ratings.OrderByDescending(tuple => tuple.Item2).ToList() - user2160375
2
如果创建一个新的列表是可以接受的,那么你可以简单地使用 .OrderByDescending(x=>x.Item2).ToList() - CodesInChaos
对于原地排序,您可以使用 list.Sort((x,y)=>Comparer<double>.Default.Compare(y.Item2,x.Item2)); - CodesInChaos
5个回答

11
您可以简单地使用。
Ratings = Ratings.OrderByDescending (t => t.Item2).ToList();

10
Ratings.OrderByDescending(t => t.Item2);

1
你应该使用 OrderByDescending() 的返回值来进行操作。 - fubo

4

您是否尝试过在列表上使用Sort方法?智能感知应该会建议您使用它,而且这种方式很自然:

Ratings.Sort((x, y) => y.Item2.CompareTo(x.Item2));
// at this stage the Ratings list will be sorted as desired

3
List<Tuple<int, double>> Ratings = new List<Tuple<int, double>>();

                    Ratings.Add(new Tuple<int, double>(1, 4.5));
                    Ratings.Add(new Tuple<int, double>(4, 1.0));
                    Ratings.Add(new Tuple<int, double>(3, 5.0));
                    Ratings.Add(new Tuple<int, double>(2, 2.5));

                    var list = Ratings.OrderByDescending(c => c.Item2).ToList();

0
var comparer = Comparer<Tuple<int, double>>.Create((x, y) => -1 * x.Item2.CompareTo(y.Item2));
Ratings.Sort(comparer);

1
乘以“-1”不是一个好主意,因为它不会改变“int.MinValue”的符号。这是比较器的有效返回值,即使双精度比较器可能不会返回该值。相反,交换“x”和“y”。 - CodesInChaos
1
List.Sort有一个重载,它接受一个Comparison<T>委托,无需构造比较器。 - CodesInChaos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接