This post will discuss how to sort a list in descending order in C#.

1. Using Enumerable.OrderByDescending() Method

With LINQ, you can use the Enumerable.OrderByDescending() method to sort all the elements of a list in descending order according to a key or a specified comparer. The following code demonstrates how to use the OrderByDescending() method to sort a list of Car objects in descending order based on the name field.

Download  Run Code

Output:

[z, 2020], [z, 2016], [y, 2015], [x, 2012]

 
Note that this creates a new, sorted copy of the list. To specify the additional sort criteria, you can call ThenBy() and ThenByDescending() method on the results of a call to OrderBy(), OrderByDescending(), ThenBy(), or ThenByDescending().

 
For example, the following code compares objects against subsequent fields, first by the name field in descending order, then by the year field in ascending order, i.e., for objects having the same name, year determines the ordering.

Download  Run Code

Output:

[z, 2016], [z, 2020], [y, 2015], [x, 2012]

2. Using Enumerable.OrderBy() Method

Alternatively, you can use LINQ’s OrderBy() method, which creates a new list with items of the source list sorted according to the specified key. It can be used as follows to sort a list of integers in descending order.

Download  Run Code

3. Using List.Sort() Method

To in-place sort contents of a list, consider using the List.Sort() method. It sorts the elements of a list using the specified comparer. The following example demonstrates its usage. Note that this doesn’t use LINQ.

Download  Run Code

 
The no-arg overload of the List.Sort() method sorts the values in ascending order. To reverse the sort order, you may invoke the List.Reverse() method on the sorted list.

Download  Run Code

That’s all about sorting lists in descending order in C#.