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

CsharpProgrammingServer Side Programming

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
raja
Published on 07-Aug-2018 10:04:23
Advertisements