You can sort an array using various methods provided by the language. Here are a few common ways to do it:
Using Array.Sort Method The Array.Sort method is a simple and efficient way to sort arrays of primitive types or objects that implement the IComparable interface:
Using Custom Comparison Logic If you need to sort based on custom logic, you can implement the IComparer<T> interface and use the Array.Sort method overload that takes an
IComparer<T> parameter:
class CustomComparer : IComparer<int>
{
public int Compare(int x, int y)
{
// Custom comparison logic
return x.CompareTo(y);
}
}
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
Array.Sort(numbers, new CustomComparer());
Result Regardless of the method you choose, the array will be sorted in ascending order by default, or in the specified order based on the comparison logic provided. Adjust the sorting logic according to your requirements.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can sort an array using various methods provided by the language.
Here are a few common ways to do it:
Using Array.Sort Method
The Array.Sort method is a simple and efficient way to sort arrays of primitive types or objects that implement the IComparable interface:
Using Array.Sort with Comparison Delegate
You can also use the Array.Sort method with a comparison delegate to define custom sorting logic:
Using LINQ OrderBy Method
If you're working with arrays of objects, you can use LINQ's OrderBy method to sort them based on a specified key:
Using LINQ OrderByDescending Method
Similarly, you can use LINQ's OrderByDescending method to sort in descending order:
Using Custom Comparison Logic
If you need to sort based on custom logic, you can implement the IComparer<T> interface and use the Array.Sort method overload that takes an IComparer<T> parameter:
Result
Regardless of the method you choose, the array will be sorted in ascending order by default, or in the specified order based on the comparison logic provided. Adjust the sorting logic according to your requirements.