How to Sort List in C#: Simple Guide with Examples
List<T>.Sort() method, which sorts the list in place in ascending order. For custom sorting, you can pass a comparison delegate or use LINQ's OrderBy() to create a sorted copy.Syntax
The basic syntax to sort a list in C# is using the Sort() method of the List<T> class. You can call it without parameters to sort in ascending order, or provide a Comparison<T> delegate to customize the order.
myList.Sort();- Sorts the list in ascending order.myList.Sort((a, b) => a.CompareTo(b));- Sorts using a custom comparison.
Alternatively, use LINQ's OrderBy() to get a new sorted sequence without changing the original list.
myList.Sort(); // Or with custom comparison myList.Sort((a, b) => a.CompareTo(b)); // Using LINQ to get a sorted copy var sortedList = myList.OrderBy(x => x).ToList();
Example
This example shows how to sort a list of integers in ascending order using Sort(). It also demonstrates sorting strings alphabetically.
using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 5, 3, 8, 1, 4 }; numbers.Sort(); Console.WriteLine("Sorted numbers: " + string.Join(", ", numbers)); List<string> fruits = new List<string> { "banana", "apple", "cherry" }; fruits.Sort(); Console.WriteLine("Sorted fruits: " + string.Join(", ", fruits)); } }
Common Pitfalls
One common mistake is expecting Sort() to return a new sorted list, but it sorts the list in place and returns void. Another pitfall is not providing a proper comparison when sorting complex objects, which can cause runtime errors or incorrect order.
Also, using OrderBy() without converting back to a list leaves you with an IEnumerable<T>, not a List<T>.
/* Wrong: expecting Sort() to return a sorted list */ List<int> nums = new List<int> {3, 1, 2}; // List<int> sortedNums = nums.Sort(); // This causes a compile error /* Right: Sort in place */ nums.Sort(); /* Wrong: sorting complex objects without comparison */ class Person { public string Name; } List<Person> people = new List<Person> { new Person { Name = "Bob" }, new Person { Name = "Alice" } }; // people.Sort(); // Throws exception /* Right: provide comparison */ people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name));
Quick Reference
Here is a quick summary of sorting methods for lists in C#:
| Method | Description | Returns |
|---|---|---|
List<T>.Sort() | Sorts the list in ascending order in place | void |
List<T>.Sort(Comparison<T>) | Sorts the list using a custom comparison | void |
Enumerable.OrderBy() | Returns a new sorted sequence without changing original list | IEnumerable<T> |
Enumerable.OrderByDescending() | Returns a new sequence sorted in descending order | IEnumerable<T> |
Key Takeaways
List<T>.Sort() to sort a list in place in ascending order.Sort() for custom sorting logic.OrderBy() to get a sorted copy without modifying the original list.Sort() returns void and modifies the list directly.