Click here to Skip to main content
Click here to Skip to main content

Tagged as

Sort on multiple values with LINQ

, 18 Sep 2010 CPOL
Rate this:
Please Sign up or sign in to vote.

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 an 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 methods OrderByDescending and ThenByDescending.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mattia Baldinger
Software Developer
Switzerland Switzerland
No Biography provided
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 4 PinmemberMichael Bakker5-May-13 4:03 
GeneralReason for my vote of 3 nothing excited Pinmembermaq_rohit10-Sep-10 20:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150123.1 | Last Updated 18 Sep 2010
Article Copyright 2010 by Mattia Baldinger
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid