Skip to main content

How to Sort from Highest to Lowest with LINQ OrderByDescending in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

players.OrderByDescending(player => player.Points) gives you the players from the most points to the fewest. The lambda picks what to sort by, and the list itself stays as it was.

Microsoft's reference: Sorts the elements of a sequence in descending order according to a key. The key is what you sort by, such as a player's points, and you pick it with a lambda. For plain numbers, the key is the number itself. The reference: To order a sequence by the values of the elements themselves, specify the identity function (x => x in C# or Function(x) x in Visual Basic) for keySelector.

Syntax​

Syntax
IOrderedEnumerable<T> <sorted> = <items>.OrderByDescending(<x> => <key>);
PartWhat it is
<items>Any sequence, such as an array or a List<T>
<x> => <key>A lambda that gets each item and returns the value to sort by, such as player => player.Points
<sorted>The items from the highest key to the lowest. <items> itself doesn't change
IOrderedEnumerable<T>The type of the result: the items, of type T, in sorted order. A foreach goes through it, and .ToList() copies it into a list

OrderBy takes the same lambda and sorts the other way. The reference: Sorts the elements of a sequence in ascending order.

The Example​

A console app called OrderByDescending sorts four temperatures from the warmest to the coldest, then four players from the most points to the fewest. Two of the players have the same points.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n OrderByDescending
cd OrderByDescending
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/OrderByDescending/OrderByDescending.csproj:
Determining projects to restore...
Restored /Users/you/source/OrderByDescending/OrderByDescending.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n OrderByDescending creates a folder named OrderByDescending with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or OrderByDescending.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the temperatures:

Program.cs (sort numbers)
// Numbers: sort them by their own value, from highest to lowest.
int[] temperatures = [18, 25, 21, 30];
Console.WriteLine(string.Join(", ", temperatures.OrderByDescending(temperature => temperature)));

temperature => temperature returns each number itself, so the numbers are sorted by their own value. string.Join puts the result on one line, with commas.

Then the players:

Program.cs (the players)
// Four players and their points.
List<Player> players =
[
new("Ana", 72),
new("Ben", 95),
new("Cleo", 88),
new("Dev", 95),
];

Each player is a Player record, declared at the end of the file, with a name and a number of points.

Then the sort:

Program.cs (sort by points)
// Sort the players from the most points to the fewest: player.Points is the key to sort by.
foreach (Player player in players.OrderByDescending(player => player.Points))
Console.WriteLine($"{player.Points} {player.Name}");

record Player(string Name, int Points);

player => player.Points is the key, so the players are sorted by their points, and foreach goes through them in that order.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
30, 25, 21, 18
95 Ben
95 Dev
88 Cleo
72 Ana

macOS-style terminal window titled Terminal — OrderByDescending showing dotnet run printing 30, 25, 21, 18 and then 95 Ben, 95 Dev, 88 Cleo and 72 Ana

The temperatures came out from 30 down to 18, and the players from 95 points down to 72. Ben and Dev both have 95, and Ben stayed before Dev, as in the list. The reference: This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.

The Complete File​

macOS-style code window titled Program.cs — OrderByDescending showing an int array of temperatures sorted with OrderByDescending by their own value, a list of four Player records with names and points, a foreach over the players sorted by Points, and the Player record

Program.cs
// Numbers: sort them by their own value, from highest to lowest.
int[] temperatures = [18, 25, 21, 30];
Console.WriteLine(string.Join(", ", temperatures.OrderByDescending(temperature => temperature)));

// Four players and their points.
List<Player> players =
[
new("Ana", 72),
new("Ben", 95),
new("Cleo", 88),
new("Dev", 95),
];

// Sort the players from the most points to the fewest: player.Points is the key to sort by.
foreach (Player player in players.OrderByDescending(player => player.Points))
Console.WriteLine($"{player.Points} {player.Name}");

record Player(string Name, int Points);

Common Mistakes​

MistakeWhat happensDo this instead
Calling OrderByDescending without using the resultThe list stayed Ana, Ben, CleoUse the result, in a foreach or kept with .ToList(), which gave Ben, Cleo, Ana
Calling OrderByDescending twice for two keysThe second call started a new sort, by name only: Dev 95, Cleo 88, Ben 95, Ana 72. The reference: Doing this introduces a new primary ordering that ignores the previously established ordering.Use ThenBy or ThenByDescending for the second key
Sorting numbers that are stored as text"9", "100" and "10" came out as 9, 100, 10: they were compared as text, not as numbersSort by the number: size => int.Parse(size) gave 100, 10, 9

FAQ​

How do I sort players with the same points by name?​

Add ThenBy after OrderByDescending. The reference: These two methods, namely ThenBy and ThenByDescending, enable you to specify additional sort criteria to sort a sequence. With Dev listed before Ben, OrderByDescending(player => player.Points).ThenBy(player => player.Name) gave Ben 95, Dev 95, Cleo 88, Ana 72.

When does the sorting happen?​

When you go through the result, not when you call OrderByDescending. The reference: The query represented by this method is not executed until the object is enumerated. A check set up the sort, then added Eve with 99 points to the list, and Eve still came first: Eve 99, Ben 95, Ana 72.

Conclusion​

OrderByDescending sorts any sequence from the highest key to the lowest, with a lambda that picks the key. Use its result, since the original list doesn't change, add ThenBy for a second key, and use OrderBy when you want the lowest first.

Additional Resources​