Sort List in-place

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;
});

EDIT: 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.

Leave a Comment