LINQ OrderBy with multiple fields

I have a list that I need to sort by two fields. I tried using OrderBy in LINQ, but that only allows me to specify a single field. I am looking for a list to sort 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 and then by first name).

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

I saw that you can use SQL syntax to accomplish this , but I'm looking for a way to do this using 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. 
+56
c # linq
Jun 15 '10 at 17:23
source share
6 answers

You need to use ThenBy :

 listOfPeople.OrderBy(person => person.LastName) .ThenBy(person => person.FirstName) 
+114
Jun 15 '10 at 17:24
source share

If you want to use the method syntax, use ThenBy() , as others suggested:

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

In the query syntax, the same thing can be done 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 actually be compiled for code that uses OrderBy() and ThenBy() , as in the first example.

Also, if you want to have OrderBy() that accepts two (or more) sort keys, you can of course write this as an extension method on IEnumerable<T> , which internally calls OrderBy() and ThenBy() .

+19
Jun 08 2018-12-12T00:
source share

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

+2
Jun 15 '10 at 17:25
source share

Use .ThenBy(aPerson=>field2);

+1
Jun 15 '10 at 17:24
source share
 var sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName).ThenBy(a => aPerson.FirstName); 
+1
Jun 15 '10 at 17:25
source share

The order of ordering the list with a larger feed is as follows:

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

You can add other fields with clasole "ThenBy"

0
Sep 20 '16 at 12:31 on
source share



All Articles