Sort List<Tuple<int, int>> 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.


Why not this?

List<Tuple<int, int>> list = ...
list = list.OrderBy(i => i.Item1).ToList();

Yes, it creates a new list, but I'm just interested - why don't you like this?


List<Tuple<int, int>> list = new List<Tuple<int, int>>
{
    new Tuple<int,int>(1,1),
    new Tuple<int,int>(0,2),
    new Tuple<int,int>(3,0)
};

list.Sort(Comparer<Tuple<int, int>>.Default);

produces:

0,2
1,1
3,0

And it's in-place, isn't it?


Now you can use lambda to do it:

list = list.OrderByDescending(x => x.Item1).ToList();

Tags:

C#

Sorting

List