Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to use ThenBy:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...