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.
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" });
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); }
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.