How to sort an ArrayList in C#?


To sort an ArrayList in C#, use the Sort() method.

The following is the ArrayList.

ArrayList arr = new ArrayList();
arr.Add(32);
arr.Add(12);
arr.Add(55);
arr.Add(8);
arr.Add(13);

Now the Sort() method is used to sort the ArrayList.

arr.Sort();

You can try to run the following code to sort an ArrayList in C#.

Example

 Live Demo

using System;
using System.Collections;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         ArrayList arr = new ArrayList();
         arr.Add(32);
         arr.Add(12);
         arr.Add(55);
         arr.Add(8);
         arr.Add(13);
         Console.Write("List: ");
         foreach (int i in arr) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.Write("Sorted List: ");
         arr.Sort();
         foreach (int i in arr) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

Output

List: 32 12 55 8 13
Sorted List: 8 12 13 32 55

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements