排序列表<元组LT; INT,INT>>到位 [英] Sort List<Tuple<int, int>> in-place
问题描述
我怎么会去按降序排列,分选列表与LT元组LT; INT,INT>>
使用决定的元组作为价值的第一要素订购?它必须是在地方,我只知道如何使用LINQ它返回一个新的列表做。
How would I go about sorting in descending order, a List<Tuple<int, int>>
using the first element of the tuple as the value that determines the order? It has to be in-place and I only know how to do it using LINQ which returns a new list.
推荐答案
您只需需要提供一个的IComparer<元组LT; INT,INT>>
或比较和LT元组LT; INT,INT>>
到列表< T>的.sort
方法。后者可能更容易指定行内:
You just need to provide an IComparer<Tuple<int, int>>
or a Comparison<Tuple<int, int>>
to the List<T>.Sort
method. The latter is probably easier to specify inline:
list.Sort((x, y) => y.Item1.CompareTo(x.Item1));
如果您想通过的第一个值,然后第二个值命令,它变得有点棘手,但仍是可行的。例如:
If you want to order by the first value and then the second value, it becomes a bit trickier, but still feasible. For example:
list.Sort((x, y) => {
int result = y.Item1.CompareTo(x.Item1));
return result == 0 ? y.Item2.CompareTo(x.Item2) : result;
});
编辑:我现在已经修改了上面的降序排列。请注意,要做到这一点,正确的方法是扭转比较(Y到X而不是X到Y)的顺序。您必须的不的只是否定的返回值的CompareTo
- 这将失败时,的CompareTo
收益 int.MinValue
。
I've now amended the above to sort in descending order. Note that the right way to do this is to reverse the order of the comparison (y to x instead of x to y). You must not just negate the return value of CompareTo
- this will fail when CompareTo
returns int.MinValue
.
这篇关于排序列表<元组LT; INT,INT>>到位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!