Multiple Sort For Collection Using LINQ

By | March 1, 2011

There are quite a lot of instance where you need to do a primary sort and you need a secondary sort on the same collection and sometimes even multiple sort. With LINQ we can achieve it pretty straight forward.

Let us assume the situation here. We have a list of employees and we need the output to be sorted by city and within every city, we need it to be sorted by the employee’s first name. Below is the code which will get your job done.

employeeList.OrderBy(item => item.FirstName).OrderBy(item => item.City);

Remember the inner sort / secondary sort has to appear first and the outer sort at the last.

Source : http://jebarson.info/post/2011/03/01/Multiple-Sort-For-Collection-Using-LINQ.aspx

Author: Jebarson

Jebarson is a consultant at Microsoft. In his overall experience of 7+ years, his expertise ranges from VB6, COM / DCOM, .net, ASP.net, WPF, WCF, SL, SQL. He has a greater love for OOA / OOD and SOA. His current focus is on Azure, Windows Phone 7, Crm and much more. He is also a frequent speaker of different community events. He blogs at http://www.jebarson.info/ . You can follow him at @Jebarson007 . Jebarson having good set of tutorials written on Windows Azure, you can found them http://bit.ly/houBNx . He is a contributor of this site and shared many tips and tricks.