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.
In python, to sort list of tuples by the first element in descending order, we have to use the sort() method with the parameter ” (reverse=True) “ which will sort the elements in descending order.
You can use one of the easiest sorting algorithm that is bubble sort. In case of tuples in tuple it will sort in order of first element of tuple. So ((32, "b"), (1, "c"), (23,"a")) Now if you sort it it will sort it in the order of 1st element of tuple.
In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method. reverse() method reverses the sequence of the list permanently.
You just need to provide an IComparer<Tuple<int, int>>
or a Comparison<Tuple<int, int>>
to the List<T>.Sort
method. The latter is probably easier to specify inline:
list.Sort((x, y) => y.Item1.CompareTo(x.Item1));
If you want to order by the first value and then the second value, it becomes a bit trickier, but still feasible. For example:
list.Sort((x, y) => {
int result = y.Item1.CompareTo(x.Item1);
return result == 0 ? y.Item2.CompareTo(x.Item2) : result;
});
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 (y
to x
instead of x
to y
). You must not just negate the return value of CompareTo
- this will fail when CompareTo
returns int.MinValue
.
Why not this?
List<Tuple<int, int>> list = ...
list = list.OrderBy(i => i.Item1).ToList();
Yes, it creates a new list, but I'm just interested - why don't you like this?
List<Tuple<int, int>> list = new List<Tuple<int, int>>
{
new Tuple<int,int>(1,1),
new Tuple<int,int>(0,2),
new Tuple<int,int>(3,0)
};
list.Sort(Comparer<Tuple<int, int>>.Default);
produces:
0,2
1,1
3,0
And it's in-place, isn't it?
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