How would I go about sorting in descending order, a List<Tuple<int, int>> using the first element of the tuple as the value that determines the order? It has to be in-place and I only know how to do it using LINQ which returns a new list.
How would I go about sorting in descending order, a List<Tuple<int, int>> using the
Share
You just need to provide an
IComparer<Tuple<int, int>>or aComparison<Tuple<int, int>>to theList<T>.Sortmethod. The latter is probably easier to specify inline:If you want to order by the first value and then the second value, it becomes a bit trickier, but still feasible. For example:
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 (
ytoxinstead ofxtoy). You must not just negate the return value ofCompareTo– this will fail whenCompareToreturnsint.MinValue.