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 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.
- 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
- Could not find an implementation of the query pattern for source type
- Filtering Collections in LINQ
- Element Operators in LINQ
Categories
Popular Posts
How to secure ASP.NET Core with NWebSec
11/07/2024
Freedash bootstrap lite
11/13/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024