How to sort a list in C#
By FoxLearn 3/5/2025 3:13:54 AM 37
There are three primary built-in methods in C# to sort a list effectively:
- OrderBy() – A LINQ method that returns an
IOrderedEnumerable
of the list items in sorted order. - List.Sort() – Sorts the list in place, modifying the original list.
- AsParallel().OrderBy() – Leverages parallel processing to sort a large list more efficiently by using multiple threads.
Sort a List with OrderBy() (LINQ)
The OrderBy() LINQ method generates an IOrderedEnumerable
that contains the items sorted in ascending order. It works for both primitive types (like integers) and complex objects. You’ll need to provide a lambda expression to specify the property by which to sort.
Here’s an example where we sort a list of Person
objects by their name:
using System.Linq; var people = new List<Person>() { new Person() { Name = "Charlie", Age = 45 }, new Person() { Name = "Anna", Age = 30 }, new Person() { Name = "John", Age = 35 }, new Person() { Name = "Alice", Age = 25 }, }; foreach (var person in people.OrderBy(p => p.Name)) { Console.WriteLine(person.Name); }
Output:
Alice Anna Charlie John
OrderBy() + ToList()
Since OrderBy() returns an IOrderedEnumerable
, you’ll need to use ToList() to convert it back to a List
.
using System.Linq; var numbers = new List<int>() { 7, 2, 4, 9, 1, 5 }; numbers = numbers.OrderBy(n => n).ToList(); Console.WriteLine(string.Join(",", numbers));
Output:
1,2,4,5,7,9
OrderByDescending() for Descending Order
The OrderBy() method sorts in ascending order by default. If you need to sort in descending order, use OrderByDescending() instead.
Here’s an example of sorting a list of integers in descending order:
using System.Linq; var numbers = new List<int>() { 7, 2, 4, 9, 1, 5 }; var sortedNumbers = numbers.OrderByDescending(n => n); Console.WriteLine(string.Join(",", sortedNumbers));
Output:
9,7,5,4,2,1
Sort a List in Place with List.Sort()
If you prefer to modify the original list directly, List.Sort() is the way to go. It sorts the list in place and uses the default comparison method for the data type. You can also pass in a custom comparison function if necessary.
Here’s an example of using List.Sort() to sort integers:
var numbers = new List<int>() { 7, 2, 4, 9, 1, 5 }; numbers.Sort(); Console.WriteLine(string.Join(",", numbers));
Output:
1,2,4,5,7,9
Sort by a Property Using List.Sort()
You can also use List.Sort() with a custom comparer.
For example, How to sort a list of people by their age:
var people = new List<Person>() { new Person() { Name = "Charlie", Age = 45 }, new Person() { Name = "Anna", Age = 30 }, new Person() { Name = "John", Age = 35 }, new Person() { Name = "Alice", Age = 25 }, }; people.Sort((a, b) => a.Age.CompareTo(b.Age)); foreach (var person in people) { Console.WriteLine($"{person.Name}, age {person.Age}"); }
Output:
Alice, age 25 Anna, age 30 John, age 35 Charlie, age 45
Sort a Large List with AsParallel().OrderBy()
For large lists, AsParallel().OrderBy() offers a way to speed up the sorting process by utilizing multiple threads. This is particularly useful when dealing with lists with more than a few hundred thousand elements.
Here's an example of using parallel sorting for a large list:
using System.Linq; var largeList = GenRandomList<int>(size: 1000000); var sortedLargeList = largeList.AsParallel().OrderBy(i => i).ToList();
Performance Considerations
Parallelization comes with overhead, so it's best to use AsParallel().OrderBy() only for sufficiently large lists (e.g., around 200k elements or more). It will be slower than the standard OrderBy() for smaller datasets but can be up to three times faster on very large datasets.
Elements | Method | Time (seconds) |
---|---|---|
10k | Single-thread | 0.0058573 |
10k | Parallel | 0.0231644 |
100k | Single-thread | 0.0318935 |
100k | Parallel | 0.0348231 |
1M | Single-thread | 0.3416384 |
1M | Parallel | 0.1355227 |
For optimal performance, stick with AsParallel() when your list has hundreds of thousands of items or more.
- How to Parser a CSV file in C#
- How to read configuration from appsettings.json in C#
- How to Programmatically Update appsettings.json in C#
- How to deconstruct an object in C#
- Handling CSV Files Without a Header Row Using CsvHelper
- CSVHelper: Header with name not found
- How to Convert a Comma-Separated String into a List of Integers in C#
- How to send synchronous requests with HttpClient in C#