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?
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.
You can use Enumerable.OrderBy and Enumerable.ThenByDescending using LINQ
var Sorted = CountList.OrderBy(l=>l.Item1)
.ThenByDescending(l => l.Item2)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With