![]() |
VOOZH | about |
Sorting is the process of arranging data in a specific order, typically ascending or descending. It helps in organizing data, making it easier to search, analyze, and process efficiently. In C#, arrays can be sorted using the Array.Sort() method.
In this article, we will focus on the most commonly used overloads of the Array.Sort() method.
This method sorts the elements of an array using the default comparison defined by the IComparable<T> interface.
Syntax:
Array.Sort<T>(T[] array);
Example:
1 2 5 8
This method sorts the elements of an array using a custom comparison logic provided by the IComparer<T> interface.
Syntax:
Array.Sort<T>(T[] array, IComparer<T> comparer);
Example:
8 5 2 1
Sort<T>(T[], int index, int length) MethodThis method sorts a specified range of elements in the array.
Syntax:
Array.Sort<T>(T[] array, int index, int length);
Example:
9 2 4 7 8
Sort<T>(T[], Comparison<T>) MethodThis method sorts the array using a delegate (Comparison<T>) that defines custom comparison logic.
Syntax:
Array.Sort<T>(T[] array, Comparison<T> comparison);
Example:
kiwi apple banana
Sort(Array, Array) MethodThis method sorts one array (keys) and rearranges the corresponding elements in another array (values).
Syntax:
Array.Sort(Array keys, Array items);
Example:
1 -> One 2 -> Two 3 -> Three
These commonly used overloads of Array.Sort() are sufficient to handle most sorting scenarios efficiently in C#.