How to Sort Array in C#: Simple Guide with Examples
In C#, you can sort an array using the
Array.Sort() method which sorts the elements in ascending order by default. For custom sorting, you can provide a comparison delegate or use LINQ methods like OrderBy().Syntax
The basic syntax to sort an array in C# is using the Array.Sort() method. It modifies the original array by sorting its elements in ascending order.
Array.Sort(array);- Sorts the entire array in ascending order.Array.Sort(array, startIndex, length);- Sorts a portion of the array.Array.Sort(array, comparer);- Sorts using a custom comparer.
csharp
Array.Sort(array);
Example
This example shows how to sort an integer array in ascending order using Array.Sort(). It prints the array before and after sorting.
csharp
using System; class Program { static void Main() { int[] numbers = { 5, 3, 8, 1, 2 }; Console.WriteLine("Before sorting: " + string.Join(", ", numbers)); Array.Sort(numbers); Console.WriteLine("After sorting: " + string.Join(", ", numbers)); } }
Output
Before sorting: 5, 3, 8, 1, 2
After sorting: 1, 2, 3, 5, 8
Common Pitfalls
Some common mistakes when sorting arrays in C# include:
- Expecting
Array.Sort()to return a new sorted array. It sorts the original array in place. - Trying to sort arrays of custom objects without implementing
IComparableor providing a comparer. - Using
OrderBy()without converting the result back to an array if you need an array.
csharp
/* Wrong: expecting Array.Sort to return a sorted array */ int[] nums = {3, 1, 2}; // int[] sorted = Array.Sort(nums); // This causes a compile error /* Right: sort in place */ Array.Sort(nums); /* Wrong: sorting custom objects without comparer */ // class Person { public string Name; } // Person[] people = ...; // Array.Sort(people); // Throws exception /* Right: provide comparer or implement IComparable */
Quick Reference
Here is a quick summary of sorting arrays in C#:
| Method | Description |
|---|---|
| Array.Sort(array) | Sorts entire array in ascending order in place |
| Array.Sort(array, startIndex, length) | Sorts a subrange of the array |
| Array.Sort(array, comparer) | Sorts using a custom comparer |
| array.OrderBy(x => x).ToArray() | Returns a new sorted array using LINQ |
Key Takeaways
Use Array.Sort() to sort arrays in place in ascending order.
Array.Sort() modifies the original array; it does not return a new one.
For custom sorting, provide a comparer or use LINQ's OrderBy.
Remember to convert LINQ results back to array if needed.
Sorting custom objects requires implementing IComparable or a comparer.