ThenByDescending Operator Part 16

ThenByDescending is one of the query operators available in linq. You can use ThenByDescending operator with linq to objects,linq to xml and linq to SQL.ThenByDescending operator is used when you want to sort by more than 1 column or property. You initially start with either orderby or orderbydescending. Since both these operators return IOrderedEnumerable<T>, you cannot reuse these operators again. This where ThenByDescending operator comes into play. ThenByDescending is an extension method which takes a keyselector delegate that returns the key which is used to sort the collection in descending order. The output collection returned from the ThenByDescending operator is of type IOrderedEnumerable<T>. Therefore if you want to sort again in descending order, you can reuse the same operator.

The prototypes for ThenByDescending operator are as follows

public static IOrderedEnumerable<T> ThenByDescending<T, K>(
this IOrderedEnumerable<T> source,
Func<T, K> keySelector)

public static IOrderedEnumerable<T> ThenByDescending<T, K>(
this IOrderedEnumerable<T> source,
Func<T, K> keySelector,
IComparer<K> comparer);

 

The only difference between these two methods are the second takes in a instance of IComparer. You would use that if you want to compare complex objects. In that case you can pass in a custom IComparer which defines how to compare two complex objects.

Let's look at an example of using ThenByDescending operator with linq to objects.

 

image

CWindowssystem32cmd.exe (3)

In the above example I am sorting sequence of names first by name and then by length in descending order. I show the example in both method or dot syntax as well as query syntax.

Let's now see an example of using ThenByDescending operator with linq to xml.

image

In the above example, I am first getting all the product elements. Once I get the product element, I sort the elements based on the name element. Sorting on name is followed by use of ThenByDescending operator to again sort by unitprice. The collection returned is an anonymous type containing Name and UnitPrice property.

You can also use ThenByDescending operator with linq to SQL queries because IQueryable Provider also defines implementation for ThenByDescending operator. ThenByDescending operator gets converted by linq to SQL provider into descending operator which SQL server can understand. Let's have a look at an example of that.

image

In the above example I am returning all the customers sorting by company name followed by contactname in descending order.

1 Comment

  • My IEnumerable would complain when I did .OredrBy(d => d.Title) when I would come to to a IEnumerable.Count(). It would say "Object must be of type string.

    Once I put a .OredrBy(d => (string)d.Title) it seems to work when checking the .Count() on the IEnumerable.

    Thanks

Comments have been disabled for this content.