How to Sort List of Objects in C# Easily
To sort a list of objects in C#, use
List.Sort() with a custom comparison method or implement IComparable in your object class. You can also use List.Sort((x, y) => x.Property.CompareTo(y.Property)) for quick sorting by a property.Syntax
You can sort a list of objects in C# using the List.Sort() method. It can be used in three main ways:
- Default sorting: Your object class implements
IComparable. - Custom comparer: Pass an
IComparerimplementation toSort(). - Lambda expression: Use a lambda to define the comparison inline.
Example syntax for lambda sorting:
list.Sort((x, y) => x.Property.CompareTo(y.Property));csharp
list.Sort((x, y) => x.Property.CompareTo(y.Property));
Example
This example shows how to sort a list of Person objects by their Age property using a lambda expression with List.Sort().
csharp
using System; using System.Collections.Generic; class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() => $"{Name}, {Age}"; } class Program { static void Main() { var people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 35 } }; // Sort by Age people.Sort((x, y) => x.Age.CompareTo(y.Age)); foreach (var person in people) { Console.WriteLine(person); } } }
Output
Bob, 25
Alice, 30
Charlie, 35
Common Pitfalls
Common mistakes when sorting lists of objects include:
- Not implementing
IComparableor providing a comparer, causingSort()to fail. - Using incorrect comparison logic that does not return a negative, zero, or positive integer properly.
- Sorting by a property that can be
nullwithout handling nulls, leading to exceptions.
Example of a wrong comparison and the correct way:
csharp
/* Wrong: returns boolean instead of int */ // people.Sort((x, y) => x.Age > y.Age); /* Correct: returns int as expected */ // people.Sort((x, y) => x.Age.CompareTo(y.Age));
Quick Reference
| Method | Description | Example |
|---|---|---|
| Implement IComparable | Define natural order inside the class | class Person : IComparable |
| Use List.Sort with IComparer | Pass a comparer object to Sort | list.Sort(new AgeComparer()); |
| Use List.Sort with Lambda | Inline comparison by property | list.Sort((x, y) => x.Age.CompareTo(y.Age)); |
Key Takeaways
Use List.Sort with a lambda expression for quick and easy sorting by object properties.
Implement IComparable in your class for natural default sorting.
Always ensure your comparison returns an int: negative, zero, or positive.
Handle null values in properties to avoid runtime errors during sorting.