Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ OrderBy with more than one field

Tags:

c#

linq

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. 
like image 820
brainimus Avatar asked Jun 15 '10 17:06

brainimus


People also ask

How do I order by two columns in Linq?

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.

How does OrderBy and ThenBy work?

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.

How to sort a list of objects c#?

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.


1 Answers

You need to use ThenBy:

listOfPeople.OrderBy(person => person.LastName)             .ThenBy(person => person.FirstName) 
like image 100
tzaman Avatar answered Sep 20 '22 15:09

tzaman