Sometimes, we may need to arrange a collection based on some criteria in ascending or descending order, for example, in an online examination system we may need to arrange students based on their scores in descending order, similarly, we may need to arrange products based on their prices in ascending order for filtering purpose in an eCommerce website, Although these can be achieved with plain c# code, we will have to code more, we will have to write sorting and searching algorithms for the same. But these requirements are so common that we need them in almost every project, that is the reason LINQ provides us some Operators for Sorting the collection, which makes our life easier.
All sorting operators are Extension method of Enumerable Class so these operators could be applied on any type of collections because every collection in .NET inherits from IEnumerable<T>
Similar to arranging a collection in ascending or descending order, we sometimes need to completely reverse the items of a collection in opposite direction, for this, we have Reverse Operator in LINQ, which simply returns the same collection arranged in opposite direction means the Last element in the collection will be the first element, and the First element will become the last element in the collection after applying Reverse Operator
The general meaning of Sorting is arranging a collection of related things based on some criteria. similarly, in LINQ, sorting operators are used to arrange the items inside a collection either in ascending or descending order and then return the sorted collection of items. The following are the different types of sorting operators available in LINQ.
• ORDER BY
• ORDER BY DESCENDING
• THEN BY
• THEN BY DESCENDING
All of the sorting operators mentioned above are used to sort a collection except the Reverse operator ,The Reverse operator simply arranges the items inside a collection in opposite direction , in other words, it simply reverse the items in a collection and return the new reversed collection. Except the Reverse() operator, all mentioned operators behave like sorting operators similar to what we have in SQL Server.
Following diagram shows the more detailed information about sorting operators in LINQ.
In our coming chapters we will discuss each of these Sorting Operators in more detail, so stay tunned.