LINQ OrderBy with more than one field

C#Linq

C# Problem Overview


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).

  • Adams, John
  • Smith, James
  • Smith, Peter
  • Thompson, Fred

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.

C# Solutions


Solution 1 - C#

You need to use ThenBy:

listOfPeople.OrderBy(person => person.LastName)
            .ThenBy(person => person.FirstName)

Solution 2 - C#

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 - C#

Your subsequent fields should be ordered by using the ThenBy() method

Solution 4 - C#

The way to order a list with more filed is the follow:

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

You can add other fields with clasole "ThenBy"

Solution 5 - C#

Use .ThenBy(aPerson=>field2);

Solution 6 - C#

var sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName).ThenBy(a => aPerson.FirstName);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrainimusView Question on Stackoverflow
Solution 1 - C#tzamanView Answer on Stackoverflow
Solution 2 - C#svickView Answer on Stackoverflow
Solution 3 - C#Ben RobinsonView Answer on Stackoverflow
Solution 4 - C#daniele3004View Answer on Stackoverflow
Solution 5 - C#RobaticusView Answer on Stackoverflow
Solution 6 - C#moi_memeView Answer on Stackoverflow