Home  >  Article  >  Backend Development  >  What is the way to sort a list in C#?

What is the way to sort a list in C#?

PHPz
PHPzforward
2023-09-12 16:13:021280browse

What is the way to sort a list in C#?

To 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");

Sort the list using Sort() method -

myList.Sort();

Example below Shows how to sort a list in C# -

Example

Live demonstration

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

The above is the detailed content of What is the way to sort a list in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete