OrderBy and OrderByDescending in LINQ

Using order by clause in LINQ is just like writing SQL query, only some syntax structure different.

IList<Country> countryList = objList .OrderBy(c=>c.Name)
.ToList<Country>();
        

We use sorting operator when we need to arrange the elements of the collection object in ascending or descending order. here you learn how to sort in linq

Sorting data using LINQ query is very easy.

LINQ OrderBy and OrderByDescending

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

Here is an example of writing orderby clause in list object.

IList<Country> countryList = objList .OrderBy(c=>c.Name)
.ToList<Country>();
               
foreach (var _cn in countryList)
{
    Console.WriteLine("CountryName {0} : Language {1}", _cn.Name, _cn.Language);
}
LINQ OrderByDescending Example

Here is an example of Order by Descending in LINQ method syntax

IList<Country> countryList = objList .OrderByDescending(c=>c.Name)
.ToList<Country>();
               
foreach (var _cn in countryList)
{
    Console.WriteLine("CountryName {0} : Language {1}", _cn.Name, _cn.Language);
}

Notice, whenever you use OrderBy or OrderByDescending clause, after that you must use ToList method to convert the entire object to a list.

 
OrderBy, OrderByDescending Examples in LINQ
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