LINQ OrderBy with more than one field
Solution 1:
You need to use ThenBy
:
listOfPeople.OrderBy(person => person.LastName)
.ThenBy(person => person.FirstName)
Solution 2:
If you want to use method syntax, use ThenBy()
, as others suggested:
listOfPeople.OrderBy(person => person.LastName)
.ThenBy(person => person.FirstName)
In query syntax, the same can be accomplished pretty much the way you wanted: two sort keys separated by a comma:
from person in listOfPeople
orderby person.LastName, person.FirstName
select person
The above code will be actually compiled to code that uses OrderBy()
and ThenBy()
, as in the first example.
Also, if you'd like to have OrderBy()
that takes two (or more) sort keys, you can certainly write that as an extension method on IEnumerable<T>
that internally calls OrderBy()
and ThenBy()
.
Solution 3:
Your subsequent fields should be ordered by using the ThenBy() method