Sort an array in descending order in C#
This post will discuss how to sort an array in descending order in C#.
1. Using Array.Sort method
The standard solution to in-place sort an array in C# is using the Array.Sort() method. It takes a comparator to compare two elements and determine which element should appear first in the final sorted array. For sorting in descending order, we can provide a custom comparison function that reverses the default sort order.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int[] array = new int[] { 5, 7, 2, 3, 9 }; Array.Sort(array, (x, y) => y.CompareTo(x)); Console.WriteLine(String.Join(", ", array)); // 9, 7, 5, 3, 2 } } |
The above solution uses a lambda expression to create an anonymous function. In older versions of C#, consider using the anonymous method feature of C# with Action<T> delegate.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { int[] array = new int[] { 5, 7, 2, 3, 9 }; Array.Sort(array, delegate(int x, int y) { return y - x; }); Console.WriteLine(String.Join(", ", array)); // 9, 7, 5, 3, 2 } } |
2. Using Enumerable.OrderByDescending method
The LINQ’s Enumerable.OrderByDescending method sorts elements of a sequence in descending order. This method avoids modifications to the original array and returns a new sorted array instead according to the specified comparator. This is the preferred method for out-of-place sorting in C#.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = new int[] { 5, 7, 2, 3, 9 }; int[] reversedSorted = array.OrderByDescending(x => x).ToArray(); Console.WriteLine(String.Join(", ", reversedSorted)); // 9, 7, 5, 3, 2 } } |
That’s all about sorting an array in descending order in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)