I have a list that I need sorted by two fields. I've tried using OrderBy in LINQ but that only allows me to specify one field. I'm looking for the list to be sorted by the first field and then if there are any duplicates in the first field to sort by the second field.
For example I want the results to look like this (sorted by last name then first name).
I've seen that you can use the SQL like syntax to accomplish this but I am looking for a way to do it with the OrderBy method.
IList<Person> listOfPeople = /*The list is filled somehow.*/ IEnumerable<Person> sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName, aPerson.FirstName); //This doesn't work.
Always make use of ThenBy() after OrderBy() because OrderBy() returns an IOrderedEnumerable which then exposes the methods ThenBy() and ThenByDescending() . This means that we can OrderBy on multiple fields by chaining OrderBy() and ThenBy() together.
The ThenBy and ThenByDescending extension methods are used for sorting on multiple fields. The OrderBy() method sorts the collection in ascending order based on specified field. Use ThenBy() method after OrderBy to sort the collection on another field in ascending order.
C# has a built-in Sort() method that performs in-place sorting to sort a list of objects. The sorting can be done using a Comparison<T> delegate or an IComparer<T> implementation.
You need to use ThenBy
:
listOfPeople.OrderBy(person => person.LastName) .ThenBy(person => person.FirstName)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With