Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / sorting

Sort on multiple values with LINQ

4.00/5 (4 votes)
18 Sep 2010CPOL 19.7K  

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:



C#
List<Person> personlist = new List<Person>() <br />{<br />    new Person(){ FirstName = "Peter", Name ="Muster", Age = 21}, <br />    new Person(){ FirstName = "Hans", Name = "Sampler", Age = 29}, <br />    new Person(){ FirstName = "Hans", Name ="Hood", Age = 34} <br />};<br /><br />IOrderedEnumerable<Person> sort = personlist.OrderBy(p => p.Age);<br />


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.



C#
var multisort = list.OrderBy(p => p.FirstName).ThenBy(p => p.Name);<br /><br />foreach (Person person in multisort)<br />{<br />    Console.WriteLine("Name {0}, FirstName {1}, Age {2}",<br />        person.Name, person.FirstName, person.Age);<br />}<br />


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)