In LINQ, sorting operators are used to rearrange the given sequence in ascending or descending order based on one or more attributes. There are 5 different types of sorting operators are available in LINQ:
OrderBy operator is used to rearranging the elements of the given sequence in ascending order. This operator by default converts the order of the given sequence in ascending order. There is no need to add an extra ascending condition in the query expression means ascending keyword is optional. You can also use the descending keyword to change the order of the given sequence in descending order.
OrderBy in Query Syntax: OrderBy operator support query syntax in both C# and VB.Net language. In query syntax, the orderby word is used as shown in the below example:
Employee Name: Anil Employee Name: Anjita Employee Name: Anju Employee Name: Rohit Employee Name: Soniya Employee Name: Supriya
OrderBy in Method Syntax: OrderBy operator in method syntax is overloaded in two different types:
- OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>): This method sort the items of the given sequence in ascending order according to the key.
- OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>): This method sort the items of the given sequence in ascending order by using a specified comparer.
It present in both the Queryable and Enumerable class. And support method syntax in both C# and VB.NET languages. As shown in the below example:
Salary of the employees: 20000 30000 40000 50000 60000 80000
In LINQ, you are allowed to sort the multiple fields of the collection in the single query and each field is separated by a comma. When you perform multiple sorting the collection first sort according to the first condition and then if the two fields in the given collection are similar then it would sort the second field and so on. As shown in the below example, emp_salary contain two similar values so the sorting is done according to emp_id.
Employee Salary: 20000 Employee Id: 209 Employee Salary: 20000 Employee Id: 210 Employee Salary: 40000 Employee Id: 211 Employee Salary: 50000 Employee Id: 214 Employee Salary: 60000 Employee Id: 213 Employee Salary: 80000 Employee Id: 212