Sort on multiple values with LINQ

With LINQ sort a collection with complex objects gets even easier than it was before. Simply use the OrderBy method of IEnumerable<T> which could look like follows.

List<Person> personlist = new List<Person>() 
new Person(){ FirstName = "Peter", Name ="Muster", Age = 21},
new Person(){ FirstName = "Hans", Name = "Sampler", Age = 29},
new Person(){ FirstName = "Hans", Name ="Hood", Age = 34}

IOrderedEnumerable<Person> sort = personlist.OrderBy(p => p.Age);

But how can I sort on multiple values, say as example first sort on name and then on prenames, so all people with the same name are ordered by their prenames. Calling the GroupBy multiple times won’t work. The answer is ThenBy.

var multisort = list.OrderBy(p => p.FirstName).ThenBy(p => p.Name);

foreach (Person person in multisort)
Console.WriteLine("Name {0}, FirstName {1}, Age {2}",
person.Name, person.FirstName, person.Age);

ThenBy is a extension method of IOrderedEnumerable<T> which is returned by the OrderBy method. Both, the OrderBy and the ThenBy method will sort ascending, to sort descending, there are the method OrderByDescending and ThenByDescending.

36 thoughts on “Sort on multiple values with LINQ

  1. Market Snapshot: U.S. stocks stall after jobless report. U.S. stocks retreated Thursday, though losses were pared significantly by the close, as weekly jobless claims disappointed and investors fretted about the methods used by banks foreclosing on mortgages.

  2. The Diocese of Buffalo’s "Journey of Faith and Grace" has led to the closings of more parishes across Western New York.

  3. calibres under its name Hardy is definitely one deployment clasp and the screw in case back Swiss

  4. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Comments are closed.