c# tuple list multiple sort

c#, list, sorting

Solution

You can use LINQ:

CountList = CountList
    .OrderBy(t => t.Item1)
    .ThenByDescending(t => t.Item2)
    .ToList();

The less comprehensible but possibly more efficient way using `List.Sort`:

CountList.Sort(
(t1, t2) =>
{
    int res = t1.Item1.CompareTo(t2.Item1);
    return res != 0 ? res : t2.Item2.CompareTo(t1.Item2);
});

`List.Sort` sorts the original list instead of creating a new one.

Problem

I have a three-dimensional tuple array: ``` var CountList = new List<Tuple<int, int, int>>(); ``` The sorting required is numerically ascending on the first int, then numerically descending on the second int, so ``` 5, 4, 7 4, 5, 6 5, 2, 3 3, 5, 2 2, 4, 1 2, 6, 4 ``` becomes ``` 2, 6 ,4 2, 4, 1 3, 5, 2 4, 5, 6 5, 4, 7 5, 2, 3 ``` Is there a way of specifying further search functions for List.Sort(), or do I need to split the information out to separate lists, perform the descending sort on each group, then add the individual list items to a "master list" in the desired ascending order?

Original source