C# Sort Arrays
Arrays often arrive in no particular order, and you may want them arranged alphabetically or from smallest to largest. C# includes helper methods in the Array class that can sort and reverse an array for you, so you rarely need to write the sorting logic yourself.
Sorting an Array
The Array.Sort() method rearranges the elements of an array in ascending order. Numbers are sorted from lowest to highest, and strings are sorted alphabetically. The method changes the original array in place rather than returning a new one.
Sorting numbers and strings
int[] numbers = {5, 1, 8, 3, 2};
Array.Sort(numbers);
foreach (int n in numbers)
{
Console.Write(n + " "); // 1 2 3 5 8
}
string[] names = {"Mia", "Amir", "Zoe"};
Array.Sort(names);
// Amir, Mia, ZoeReversing an Array
The Array.Reverse() method flips the order of the elements. A common trick is to sort first and then reverse, which gives you the elements in descending order.
Sort then reverse for descending order
int[] numbers = {5, 1, 8, 3, 2};
Array.Sort(numbers); // 1 2 3 5 8
Array.Reverse(numbers); // 8 5 3 2 1
foreach (int n in numbers)
{
Console.Write(n + " "); // 8 5 3 2 1
}Other Helpful Array Methods
Useful Array methods
Finding a value with IndexOf
string[] fruits = {"apple", "banana", "cherry"};
int position = Array.IndexOf(fruits, "banana");
Console.WriteLine(position); // 1