How to sort a list in C#?

CsharpProgrammingServer Side Programming

Set a list with some values. Here, we have a list of strings.

var cars = new List<string>() {"Mercedes", "Audi", "Jaguar" };

To sort, simply use Sort() method.

cars.Sort();

The following is an example showing how to sort a list in C#.

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      var cars = new List<string>() {"Mercedes", "Audi", "Jaguar" };
      Console.WriteLine("Original Array =");
      foreach (var name in cars) {
         Console.WriteLine(name);
      }
      // sort
      cars.Sort();
      Console.WriteLine("Sorted Array =");
      foreach (var name in cars) {
         Console.WriteLine(name);
      }
   }
}

Output

Original Array =
Mercedes
Audi
Jaguar
Sorted Array =
Audi
Jaguar
Mercedes
raja
Published on 18-Sep-2018 13:04:48
Advertisements