LINQ ThenBy and ThenByDescending Example

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 ThenByDescending in LINQ Query

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.

LINQ ThenBy Example

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);
}
LINQ ThenByDescending Example

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.

 
ThenBy in LINQ Query: Linq ThenByDescending Example C#
LINQ (language integrated query) allow you to write query on database objects like ado.net, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join Asp.net MVC Course