3 Ways To Sort A C# List

C# is a popular programming language and one of its most commonly used data structures is the List. The List is a dynamic array that can store a collection of objects or elements. However, when working with large data sets, it is important to be able to sort the elements in the List so that the data can be easily analyzed and processed.

There are several ways to sort a C# List and in this article, we will explore the most common methods for sorting a List.

Method 1. Sort Method

The simplest way to sort a C# List is by using the Sort method. This method is available in the List class and it sorts the elements in the List in ascending order by default. The syntax for using the Sort method is as follows: 

List<int> numbers = new List<int> {5, 2, 9, 1, 6};
numbers.Sort();

Method 2. Sort with a Comparison Function

In some cases, you may want to sort the List based on custom comparison logic. In this scenario, you can use the Sort method along with a comparison function. The comparison function is defined using the Comparison delegate and it should return an integer that represents the relative order of the two elements being compared. The syntax for using the Sort method with a comparison function is as follows:

List<string> names = new List<string> { "John", "Mike", "Alex", "Emily" };
names.Sort((x, y) => x.Length.CompareTo(y.Length));

Method 3. OrderBy and ThenBy

Another way to sort a C# List is by using the OrderBy and ThenBy LINQ methods. The OrderBy method sorts the elements in the List in ascending order based on the specified key, while the ThenBy method sorts the elements based on additional keys in ascending order. The syntax for using the OrderBy and ThenBy methods is as follows:

List<Employee> employees = new List<Employee> {
    new Employee { Name = "John", Age = 30, Salary = 6000 },
    new Employee { Name = "Mike", Age = 25, Salary = 5000 },
    new Employee { Name = "Alex", Age = 35, Salary = 7000 },
    new Employee { Name = "Emily", Age = 28, Salary = 6000 }
};

var sortedEmployees = employees.OrderBy(x => x.Age).ThenBy(x => x.Salary).ToList();

Sorting a C# List is a common task that can be achieved in several ways, including the Sort method, the Sort method with a comparison function, and the OrderBy and ThenBy LINQ methods. Choose the method that best fits your requirements and start organizing your data sets with ease.


Similar Articles