How to use multiple "order by" in LINQ?
How to use multiple "order by" in LINQ?
222
17-Aug-2023
Aryan Kumar
18-Aug-2023To use multiple
OrderBy()in LINQ, you can use theThenBy()method. TheThenBy()method takes a lambda expression as its parameter and sorts the list by the property specified by the lambda expression. The following code sorts a list ofPersonobjects by their age in ascending order, and then by their name in descending order:C#
In this code, the
OrderBy()method sorts the list by theAgeproperty of thePersonobjects in ascending order. TheThenBy()method then sorts the list by theNameproperty of thePersonobjects in descending order.You can also use the
ThenByDescending()method to sort the list by the property specified by the lambda expression in descending order. The following code is equivalent to the previous code:C#