How to sort an array in C#?


We can sort a one-dimensional array in two ways, using Array.Sort() method and using LINQ query.

Array.Sort()

Array is the static helper class that includes all utility methods for all types of array in C#. The Array.Sort() method is used to sort an array in different ways.

The following example sorts an array in ascending order.

Example: Sort an Array
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };

Array.Sort(animals); // Result: ["Alligator", "Bear", "Cat","Donkey","Elephant","Fox","Goat"]

The following example sorts only the first three elements of an array.

Example: Sort the Portion of Array
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
          
Array.Sort(animals, 0, 3); // Result: ["Alligator","Cat","Fox", "Donkey", "Bear", "Elephant", "Goat"]

In the above example, we passed starting index 0 and length 3. So, it will sort three elements starting from index 0.

The following example sorts two different arrays where one array contains keys, and another contains values.

Example: Sort Keys and Values
int[] numbers = { 2, 1, 4, 3 };
String[] numberNames = { "two", "one", "four", "three" };

Array.Sort(numbers, numberNames);

Array.ForEach<int>(numbers, n => Console.WriteLine(n));//[1,2,3,4]
Array.ForEach<string>(numberNames, s => Console.WriteLine(s));//["one", "two", "three", "four"]

The Array.Reverse() method reverses the order of the elements in a one-dimensional Array or in a portion of the Array. Note that it does not sort an array in descending order but it reverses the order of existing elements.

Example: Sort an Array in Descending Order
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
 
Array.Reverse(animals);// Result: ["Goat", "Fox", "Elephant", "Donkey", "Cat", "Bear", "Alligator"]

Thus, the Array.Sort() method is easy to use and performs faster than LINQ queries.

Sort an Array using LINQ

An array can be sort using LINQ.

Example: Sort an Array using LINQ
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
 
var sortedStr = from name in animals
                orderby name
                select name;
 
Array.ForEach<string>(sortedStr.ToArray<string>(), s => Console.WriteLine(s)); 

You can sort an array in descending order easily.

Example: Sort an Array using LINQ
var sortedStr = from name in animals
                orderby name descending 
                select name;
  
Array.ForEach<string>(sortedStr.ToArray<string>(), s => Console.WriteLine(s)); // Result: ["Goat", "Fox", "Elephant", "Donkey", "Cat", "Bear", "Alligator"]