How to sort by multiple fields in Linq

By FoxLearn 2/10/2025 8:07:07 AM   44
In LINQ (Language Integrated Query), you can sort by multiple fields using the OrderBy and ThenBy methods.

OrderBy is used for the primary sorting, and ThenBy (or ThenByDescending if you need descending order) is used for secondary sorting and beyond.

Suppose you have a collection of Person objects, and you want to sort first by Age (ascending), and then by Name (ascending).

For example, sort by multiple fields in LINQ

var people = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "John", Age = 22 },
    new Person { Name = "Alice", Age = 30 }
};

var sortedPeople = people
    .OrderBy(p => p.Age)       // First sort by Age in ascending order
    .ThenBy(p => p.Name)       // Then sort by Name in ascending order
    .ToList();

foreach (var person in sortedPeople)
{
    Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}

Output:

Name: Jane, Age: 25
Name: John, Age: 22
Name: Alice, Age: 30
Name: John, Age: 30

If you want to sort Age in descending order and then Name in ascending order, you can use OrderByDescending:

var sortedPeople = people
    .OrderByDescending(p => p.Age)  // Sort by Age descending
    .ThenBy(p => p.Name)             // Then sort by Name ascending
    .ToList();

In this example:

  • OrderBy(p => p.Age) sorts the people by Age in ascending order.
  • ThenBy(p => p.Name) sorts the people by Name in ascending order if two people have the same Age.
  • You can chain multiple ThenBy or ThenByDescending calls if you want more sorting levels.