How to sort elements in a collection using the LINQ extension methods?
How to sort elements in a collection using the LINQ extension methods?
18503-Nov-2023
Updated on 05-Nov-2023
Home / DeveloperSection / Forums / How to sort elements in a collection using the LINQ extension methods?
How to sort elements in a collection using the LINQ extension methods?
Aryan Kumar
05-Nov-2023You can sort elements in a collection using LINQ extension methods like OrderBy, OrderByDescending, and ThenBy for additional sorting criteria. Here's how to do it:
Assuming you have a collection of objects and want to sort them based on a specific property, follow these steps:
Import the LINQ namespace at the beginning of your code:
Use the LINQ OrderBy or OrderByDescending extension methods to perform the initial sorting. Here's an example using OrderBy to sort a collection of objects by a property called "Name" in ascending order:
If you need to sort by multiple criteria, use the ThenBy or ThenByDescending extension methods after the initial sorting. Here's an example using ThenBy to sort by a second property (e.g., "Age") in ascending order:
You can use ThenByDescending for descending sorting based on additional criteria.
If you want to sort the collection in place, you can use the ToList() method to convert the sorted sequence back to a list:
This step is optional; you can keep the sorted collection as an IEnumerable if you don't need to modify it.
Here's a complete example that demonstrates sorting a collection of objects by name and age using LINQ extension methods:
This code sorts a list of Person objects first by name and then by age, and it prints the sorted results.