OrderByDescending is one of the ordering query operators available in linq.You can use OrderByDescending operator with linq to objects, linq to XML and linq to SQL. OrderByDescending operator can be used in method or dot syntax as well as query syntax which is more of a SQL like syntax.
OrderByDescending operator is an extension method available on any objects that implements IEnumerable<T> or IQueryable<T>. IEnumerable<T> applies to queries based on linq to objects or linq to XML. When OrderByDescending operator is used with IQueryable, the query gets translated to SQL and Linq provider for SQL server transform the OrderByDescending operator into descending keyword which SQL server can understand.
The prototype for OrderByDescending operator looks like this
public static IOrderedEnumerable<T> OrderByDescending<T, K>(
this IEnumerable<T> source,
Func<T, K> keySelector)
K : IComparable<K>;
Sorting is done based on the key returned by the key selector delegate. OrderByDescending operator requires that keyselector to return a key that must implement IComparable so it can call the compareto method to determine if two elements with in a sequence are equal to, less than or greater than. Once the key is returned by the key selector delegate the output sequence is sorted based on the key in descending order. The output returned by OrderByDescending operator implements IOrderedEnumerable<T>. This means that you can only use OrderByDescending in the first sort because it requires the input sequence to implement IEnumerable<T>.
Let's start of with an example that uses linq to objects.
In the above example I am sorting all the integers in descending order. I am also showing the example in both query syntax as well as method syntax.
Let's now look at an example of using OrderByDescending operator with linq to XML.
In the above example, I make use of orderby query operator in linq to XML to order the products based on unit price in descending order.
We can also use OrderByDescending operator with linq to SQL queries. In that case linq to SQL provider will convert the linq to queries into descending operator which SQL server can understand.
In the above example I make use of OrderByDescending operator with linq to SQL query. In the query I am sorting all the products in descending order based on their unit price.