How to sort an ArrayList in C#?

CsharpProgrammingServer Side Programming

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
raja
Published on 18-Sep-2018 12:02:18
Advertisements