How to sort a List in C#

Introduction

The List class has a lot of useful methods that you can use to organize data. This article will cover how to sort the items in your list and make them easier to read. The Sort method is the simplest way to sort a C# list. The Sort method has four overloaded forms.

Sort(Int32, Int32, IComparer<T>)   Sorts the elements in a range of elements in List<T> using the specified comparer.
Sort()     Sorts the elements in the entire List<T> using the default comparer.
Sort(IComparer<T>)     Sorts the elements in the entire List<T> using the specified comparer.
Sort(Comparison<T>) Sorts the elements in the entire List<T> using the specified Comparison<T>.

The Sort method of List<T> sorts all items of the List using the QuickSort algorithm.

The following code example in Listing 1 sorts List items and displays both the original order and sorted order of the List items.

// List of string  
List<string> authors = new List<string>(5);  
authors.Add("Mahesh Chand");  
authors.Add("Chris Love");  
authors.Add("Allen O'neill");  
authors.Add("Naveen Sharma");  
authors.Add("Mahesh Chand");  
authors.Add("Monica Rathbun");  
authors.Add("David McCarter");  
  
Console.WriteLine("Original List items");  
Console.WriteLine("===============");  
// Print the original order  
foreach (string a in authors)  
Console.WriteLine(a);  
  
// Sort list items  
authors.Sort();  
  
Console.WriteLine();  
Console.WriteLine("Sorted List items");  
Console.WriteLine("===============");  
// Print sorted items  
foreach (string a in authors)  
Console.WriteLine(a);  

Listing 1.

The output of Listing 8 looks like Figure 1.

We can also use the OrderBy method to sort a List in C#. The OrderBy gives you a sorted version of a list. The sorted list can be used as input to the TakeWhile, SkipWhile and Reverse methods.

List<int> sorted = L.OrderBy(i => i);

Here is a detailed article on sorting a List using OrderBy and other methods: 3 Ways To Sort A C# List (c-sharpcorner.com).

Next: C# List Tutorial


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.