How to sort by multiple fields in Linq
By Tan Lee Published on Feb 10, 2025 107
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 byAge
in ascending order.ThenBy(p => p.Name)
sorts the people byName
in ascending order if two people have the sameAge
.- You can chain multiple
ThenBy
orThenByDescending
calls if you want more sorting levels.
- C# LINQ Tutorial
- C# LINQ query and method syntax
- Group by in LINQ
- How to get the index of an element in C# LINQ
- Cannot use a lambda expression as an argument to a dynamically dispatched operation
- How to group by multiple columns using LINQ
- Using LINQ to remove elements from a List<T>
- How to Find XML element by name with XElement in LINQ
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Motiv MUI React Admin Dashboard Template
Nov 19, 2024
K-WD Tailwind CSS Admin Dashboard Template
Nov 17, 2024