Thursday, September 01, 2011

Sort in descending order with multiple columns using LINQ to Object, C#.NET 4.0


Sort in descending order with multiple columns using LINQ to Object, C#.NET 4.0

Below the example of sorting list object in descending order with multiple columns.

NameSpace

using System.Linq;

C#.NET

List<Country> countryList = new List<Country>();

Load countryList Object from source

Descending Order

countryList = countryList.OrderByDescending(c => c.Column1).ThenByDescending(c => c.Column2).ToList<Country>();

Ascending Order (Default)

countryList = countryList.OrderBy(c => c.Column1).ThenBy(c => c.Column2).ToList<Country>();

Note:  For more than 2 columns, you can again use “.ThenBy” clause for column3, column4 etc.

No comments: