What is the method for sorting a list in C#?


The sort a list in C#, use the Sort() method.

Let us first create a list −

List<string> myList = new List<string>();

Now add elements −

myList.Add("Audi");
myList.Add("BMW");
myList.Add("Chevrolet");
myList.Add("Hyundai");

Use the Sort() method to sort the list −

myList.Sort();

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

Example

 Live Demo

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      List<string> myList = new List<string>();

      myList.Add("Audi");
      myList.Add("BMW");
      myList.Add("Chevrolet");
      myList.Add("Hyundai");

      myList.Sort();

      foreach (string value in myList) {
         Console.WriteLine(value);
      }
   }
}

Output

Audi
BMW
Chevrolet
Hyundai

Updated on: 20-Jun-2020

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements