How to use the Sort() method of array class in C#?


The Sort() method sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

Set the array.

int[] list = { 22, 12, 65, 9};

Use the Sort() method to sort the array.

Array.Sort(list);

The following is an example to learn how to work with the Sort() method.

Example

 Live Demo

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         int[] list = { 22, 12, 65, 9};
         Console.Write("Original Array: ");
         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         //sort the array
         Array.Sort(list);
         Console.Write("Sorted Array: ");
         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

Output

Original Array: 22 12 65 9
Sorted Array: 9 12 22 65

Updated on: 23-Jun-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements