How to Sort in Descending Order in C# - Simple Guide
In C#, you can sort collections in descending order using
OrderByDescending for LINQ queries or Array.Sort with a custom comparer. For example, myList.OrderByDescending(x => x) sorts a list from highest to lowest.Syntax
To sort a collection in descending order, you can use the following syntax:
collection.OrderByDescending(x => x.Property)- sorts using LINQ by a property or value.Array.Sort(array, (a, b) => b.CompareTo(a))with a custom comparer for descending order.
The OrderByDescending method returns a new sorted sequence without changing the original collection.
csharp
var sortedDescending = collection.OrderByDescending(x => x.Property);Example
This example shows how to sort a list of numbers in descending order using OrderByDescending and how to sort an array using Array.Sort with a custom comparer.
csharp
using System; using System.Linq; class Program { static void Main() { // Using OrderByDescending with a list var numbers = new[] { 5, 3, 8, 1, 9 }; var sortedList = numbers.OrderByDescending(n => n); Console.WriteLine("Sorted list descending:"); foreach (var num in sortedList) { Console.Write(num + " "); } Console.WriteLine(); // Using Array.Sort with custom comparer int[] array = { 5, 3, 8, 1, 9 }; Array.Sort(array, (a, b) => b.CompareTo(a)); Console.WriteLine("Sorted array descending:"); foreach (var num in array) { Console.Write(num + " "); } } }
Output
Sorted list descending:
9 8 5 3 1
Sorted array descending:
9 8 5 3 1
Common Pitfalls
Common mistakes when sorting descending in C# include:
- Using
OrderByinstead ofOrderByDescending, which sorts ascending. - Modifying the original collection expecting
OrderByDescendingto sort in place (it returns a new sequence). - Using
Array.Sortwithout a custom comparer, which sorts ascending by default.
Always check if you need a new sorted sequence or to sort in place.
csharp
/* Wrong: sorts ascending */ var wrongSort = numbers.OrderBy(n => n); /* Right: sorts descending */ var rightSort = numbers.OrderByDescending(n => n); /* Wrong: sorts ascending by default */ Array.Sort(array); /* Right: sorts descending with comparer */ Array.Sort(array, (a, b) => b.CompareTo(a));
Quick Reference
| Method | Description | Example |
|---|---|---|
| OrderByDescending | Returns a new sequence sorted descending | myList.OrderByDescending(x => x) |
| Array.Sort with comparer | Sorts array in place descending | Array.Sort(array, (a,b) => b.CompareTo(a)) |
Key Takeaways
Use OrderByDescending to get a new sorted sequence in descending order.
Array.Sort sorts in place and needs a custom comparer for descending order.
OrderBy sorts ascending by default, so use OrderByDescending for descending.
OrderByDescending does not modify the original collection.
Always verify if you want a new sorted collection or to sort the existing one.