sort array in csharp

To sort an array in C#, you can use the Array.Sort() method. This method sorts the elements of an array in ascending order by default. Here is an example:

main.cs
int[] numbers = { 7, 3, 9, 2, 6 };

Array.Sort(numbers);

foreach (int num in numbers)
{
    Console.Write(num + " "); // Output: 2 3 6 7 9
}
142 chars
9 lines

If you want to sort the elements of the array in descending order, you can use the Array.Reverse() method after sorting:

main.cs
int[] numbers = { 7, 3, 9, 2, 6 };

Array.Sort(numbers);
Array.Reverse(numbers);

foreach (int num in numbers)
{
    Console.Write(num + " "); // Output: 9 7 6 3 2
}
166 chars
10 lines

related categories

gistlibby LogSnag