C # list of tuples with multiple sortings

I have a three-dimensional array of tuples:

var CountList = new List<Tuple<int, int, int>>();

The required sort numerically increases on the first int, and then numerically decreases on the second int, therefore

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 to specify additional search functions for List.Sort (), or do I need to divide the information into separate lists, sort in descending order in each group, and then add individual list items to the "master" list "in the desired ascending order?

+4
source share
4 answers

You can use LINQ:

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

A less clear, but possibly more effective way to use it 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 source list instead of creating a new one.

+5

Enumerable.OrderBy Enumerable.ThenByDescending LINQ

var Sorted = CountList.OrderBy(l=>l.Item1)
                      .ThenByDescending(l => l.Item2)
                      .ToList();
0

you can use

List<Tuple<int, int, int>> Sorted
  = CountList.OrderBy( iTuple => iTuple.Item1 )
             .ThenByDescending( iTuple => iTuple.Item2 )
             .ToList();

or implement a custom mapper to get lexicographical ordering.

0
source

Sorting has an overload that takes a comparison parameter.

CountList.Sort((t1, t2) => {
        int c = t1.Item1.CompareTo(t2.Item1);
        if (c != 0) return c;
        c = t1.Item2.CompareTo(t2.Item2);
        return -c;
    }
);
0
source

Source: https://habr.com/ru/post/1542897/


All Articles