Sort an Array in C#

This article will introduce different methods to sort an array in C#.

Use the Array.Sort() Method to Sort an Array in C#

We will use the method Array.Sort() to sort an array. The Array.Sort() method sorts the array in ascending order. There are multiple overloads of this method. The correct syntax to use this method is as follows.

Java-S: Bài 41. Sắp xếp (Sort)...
Java-S: Bài 41. Sắp xếp (Sort) trong Collection sử dụng Collections.sort()
Array.Sort(Array array);

This overload of the method Sort() has one parameter only. The detail of its parameter is as follows

Parameters Description
array mandatory This is the array that we want to sort.

This function sorts the array in ascending order.

The program below shows how we can use the Sort() method to sort an array.

using System; 
  
class Sort { 
      public static void Main() 
    { 
        int[] arr = new int[] {2, 10, 5, 8, 4, 11}; 
        Console.WriteLine("Array Before Sorting:\n");
        foreach(int value in arr) 
        { 
            Console.Write(value + " "); 
        } 
        Console.WriteLine("\n");
        Array.Sort(arr); 
        Console.WriteLine("Array After Sorting:\n"); 
        foreach(int value in arr) 
        { 
            Console.Write(value + " "); 
        } 
    } 
} 

Output:

Array Before Sorting:

2 10 5 8 4 11 

Array After Sorting:

2 4 5 8 10 11 

Related Article - Csharp Array

  • Get the Length of an Array in C#
  • Sort an Array in Descending Order in C#
  • Remove Element of an Array in C#