Array.Sort() / Array.Reverse()
The Array.Sort() method sorts an array in ascending order, and Array.Reverse() reverses the order of the elements in an array.
Syntax
// Sorts the entire array in ascending order (modifies the original array). Array.Sort(T[] array) // Sorts a range of elements starting at index for length elements. Array.Sort(T[] array, int index, int length) // Reverses the order of all elements in the array (modifies the original array). Array.Reverse(T[] array) // Reverses a range of elements starting at index for length elements. Array.Reverse(T[] array, int index, int length)
Method List
| Method | Description |
|---|---|
| Array.Sort(T[] array) | Sorts the entire array in ascending order using the default comparison (numeric order for numbers, lexicographic order for strings). |
| Array.Sort(T[] array, int index, int length) | Sorts only the specified range of the array in ascending order. |
| Array.Reverse(T[] array) | Reverses the order of all elements in the array. |
| Array.Reverse(T[] array, int index, int length) | Reverses only the specified range of the array. |
Sample Code
using System;
// Sort a numeric array in ascending order using Array.Sort().
int[] scores = { 78, 92, 45, 88, 61 };
Array.Sort(scores);
Console.WriteLine(string.Join(", ", scores)); // 45, 61, 78, 88, 92
// Sort in descending order by calling Reverse() after Sort().
Array.Reverse(scores);
Console.WriteLine(string.Join(", ", scores)); // 92, 88, 78, 61, 45
// String arrays can also be sorted (lexicographic order).
string[] fruits = { "cherry", "apple", "banana", "date" };
Array.Sort(fruits);
Console.WriteLine(string.Join(", ", fruits)); // apple, banana, cherry, date
// Sort only a portion of the array (3 elements starting at index 1).
int[] data = { 10, 50, 30, 20, 40 };
Array.Sort(data, 1, 3); // Sorts only [1] through [3] (50, 30, 20).
Console.WriteLine(string.Join(", ", data)); // 10, 20, 30, 50, 40
// The original array is modified. Copy it first if you need to preserve the original.
int[] original = { 3, 1, 4, 1, 5 };
int[] copy = (int[])original.Clone();
Array.Sort(copy);
Console.WriteLine(string.Join(", ", original)); // 3, 1, 4, 1, 5 (unchanged)
Console.WriteLine(string.Join(", ", copy)); // 1, 1, 3, 4, 5
Notes
Both Array.Sort() and Array.Reverse() modify the original array in place. If you need to preserve the original array, create a copy first using Array.Copy() or Clone() before sorting or reversing.
If you need a custom sort order (for example, sorting objects by a specific property), you can pass a lambda expression to Array.Sort(array, Comparison<T> comparison).
For copying arrays, see Array.IndexOf() / Array.Copy().
If you find any errors or copyright issues, please contact us.