0
0
CsharpHow-ToBeginner · 4 min read

How to Sort List of Objects in C# Easily

In C#, you can sort a list of objects using List.Sort() with a custom Comparison delegate or by implementing IComparable in your class. Alternatively, use LINQ's OrderBy method for a simple and readable way to sort by object properties.
📐

Syntax

There are two common ways to sort a list of objects in C#:

  • Using List.Sort with Comparison: list.Sort((x, y) => x.Property.CompareTo(y.Property));
  • Using LINQ OrderBy: var sorted = list.OrderBy(obj => obj.Property).ToList();

In both, Property is the object field you want to sort by.

csharp
list.Sort((x, y) => x.Property.CompareTo(y.Property));

var sorted = list.OrderBy(obj => obj.Property).ToList();
💻

Example

This example shows how to sort a list of Person objects by their Age property using both List.Sort and LINQ OrderBy.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public 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 using List.Sort with Comparison delegate
        people.Sort((x, y) => x.Age.CompareTo(y.Age));
        Console.WriteLine("Sorted by Age using List.Sort:");
        foreach (var person in people)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }

        // Sort using LINQ OrderBy
        var sortedByName = people.OrderBy(p => p.Name).ToList();
        Console.WriteLine("\nSorted by Name using LINQ OrderBy:");
        foreach (var person in sortedByName)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
    }
}
Output
Sorted by Age using List.Sort: Bob - 25 Alice - 30 Charlie - 35 Sorted by Name using LINQ OrderBy: Alice - 30 Bob - 25 Charlie - 35
⚠️

Common Pitfalls

Common mistakes when sorting lists of objects include:

  • Not providing a comparison method or IComparable implementation, causing List.Sort() to throw an exception.
  • Sorting the original list unintentionally when you want a sorted copy (use LINQ OrderBy to get a new list).
  • Comparing properties incorrectly, such as mixing ascending and descending logic.

Always ensure the comparison logic matches your sorting goal.

csharp
/* Wrong: No comparison provided, causes runtime error */
// people.Sort(); // Error if Person does not implement IComparable

/* Right: Provide comparison delegate */
people.Sort((x, y) => x.Age.CompareTo(y.Age));
📊

Quick Reference

MethodUsageModifies Original ListReturns New List
List.Sort(Comparison)Sorts list in place using a comparison delegateYesNo
List.Sort() with IComparableSorts list in place if objects implement IComparableYesNo
LINQ OrderByReturns a new sorted list by a key selectorNoYes
LINQ OrderByDescendingReturns a new list sorted descending by a keyNoYes

Key Takeaways

Use List.Sort with a comparison delegate or IComparable to sort lists in place.
Use LINQ OrderBy to get a new sorted list without changing the original.
Always compare the correct property and ensure comparison logic matches desired order.
Avoid runtime errors by providing a comparison method if your class does not implement IComparable.
Choose List.Sort for performance and LINQ OrderBy for readability and chaining.