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

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

PHPz
Release: 2023-09-12 16:13:02
forward
1346 people have browsed it

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>();
Copy after login

Now add elements -

myList.Add("Audi");
myList.Add("BMW");
myList.Add("Chevrolet");
myList.Add("Hyundai");
Copy after login

Sort the list using Sort() method -

myList.Sort();
Copy after login

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);
      }
   }
}
Copy after login

Output

Audi
BMW
Chevrolet
Hyundai
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template