When we have more than one field to be used in order by clause, there we use then by, for each additional order by field we can use thenby or thenbyDescending.
Here you learn How to use ThenBy and ThenByDescending in LINQ Query using C#.
IList<Country> countryList = objList .OrderByDescending(c=>c.Name) .ThenByDescending(c=>c.Language) .ToList<Country>();
We use sorting operator when we need to arrange the elements of the collection object in ascending or descending order.
ThenBy and ThenByDescending are extension methods.
In LINQ we can do multiple sorting for different fields, method syntax is supported by using ThenBy and ThenByDescending.
Here we have an IList collection object with some sample data we use in examples below
IList<Country> objList = new List<Country>(); objList.Add(new Country() { Name="India", Language="English" }); objList.Add(new Country() { Name = "USA", Language = "English" }); objList.Add(new Country() { Name = "UK", Language = "English" }); objList.Add(new Country() { Name = "Australia", Language = "English" }); objList.Add(new Country() { Name = "Canada", Language = "Mandarin" }); objList.Add(new Country() { Name = "New Zeland", Language = "English" }); objList.Add(new Country() { Name = "Dubai", Language = "Arabic" }); objList.Add(new Country() { Name = "Spain", Language = "Spanish" }); objList.Add(new Country() { Name = "Russia", Language = "Russian" });
We can use ThenBy after OrderBy or OrderByDescending Only.
Here is an example of writing ThenBy clause in list object.
IList<Country> countryList = objList .OrderBy(c=>c.Name) .ThenBy(c=>c.Language) .ToList<Country>(); foreach (var _cn in countryList) { Console.WriteLine("CountryName {0} : Language {1}", _cn.Name, _cn.Language); }
Here is and example of ThenByDescending clause in c# list object.
IList<Country> countryList = objList .OrderByDescending(c=>c.Name) .ThenByDescending(c=>c.Language) .ToList<Country>(); foreach (var _cn in countryList) { Console.WriteLine("CountryName {0} : Language {1}", _cn.Name, _cn.Language); }
Notice, whenever you use ThenBy or ThenByDescending clause, after that you must use ToList method to convert the entire object to a list.