Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# tuple list multiple sort

Tags:

c#

list

sorting

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?

like image 628
David Smithson Avatar asked Feb 13 '23 20:02

David Smithson


2 Answers

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.

like image 173
Tim Schmelter Avatar answered Feb 15 '23 08:02

Tim Schmelter


You can use Enumerable.OrderBy and Enumerable.ThenByDescending using LINQ

var Sorted = CountList.OrderBy(l=>l.Item1)
                      .ThenByDescending(l => l.Item2)
                      .ToList();
like image 38
Adil Avatar answered Feb 15 '23 09:02

Adil