Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order. Alternatively for sorted() , you can use the following code.
The ASC command is used to sort the data returned in ascending order.
With Linq
var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);
Without Linq
li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort
Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like
li = li.OrderBy(i => i).ToList();
Without Linq:
Ascending:
li.Sort();
Descending:
li.Sort();
li.Reverse();
without linq,
use Sort()
and then Reverse()
it.
I was checking all the answer above and wanted to add one more additional information. I wanted to sort the list in DESC order and I was searching for the solution which is faster for bigger inputs and I was using this method earlier :-
li.Sort();
li.Reverse();
but my test cases were failing for exceeding time limits, so below solution worked for me:-
li.Sort((a, b) => b.CompareTo(a));
So Ultimately the conclusion is that 2nd way of Sorting list in Descending order is bit faster than the previous one.
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