tags:

views:

186

answers:

4

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.
+10  A: 

You need to use ThenBy:

listOfPeople.OrderBy(person => person.LastName)
            .ThenBy(person => person.FirstName)
tzaman
A full explanation is listed here: http://weblogs.asp.net/zeeshanhirani/archive/2008/04/16/thenby-operator-part-14.aspx
Greg Bahrey
A: 

Use .ThenBy(aPerson=>field2);

Robaticus
A: 
var sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName).ThenBy(a => aPerson.FirstName);
moi_meme
A: 

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

Ben Robinson