A few days ago, I was working on some Entity Framework stuff where I encountered the following logic for applying sort expressions to the EF query:

I felt it was an awful lot of code and code repetition especially when you are working with LINQ and extension methods, its just against the spirit of it.

So I thought what if we create a generic extension method that can take an IQueryable and apply sorting on it, taking into account if the IQueryable expression was already sorted. My first attempt started with something like the following:

However it failed on any of the following lines:

generating an exception. As I poked around scratching my head, I realised an IQueryable instance is always cast’able to an IOrderedQueryable instance even when no sort expression has been applied on an IQueryable instance atleast once. So now the challenge was to figure out if an IQueryable had already sort expression applied to it. This was essential to decide whether to invoke the ThenBy sort methods or the OrderBy sort methods.

Luckily I found the IQueryable.Expression.Type.Name property which stored the actual type name of the instance represented by query, and the type name differed for an IQueryable instance vs an IOrderedQueryable instance. This proved all that was needed to complete the generic sort method successfully:

And the above method helped us reduce our sorting expressions to the following:

A whole lot compact and concise I hope you would agree.

Share this: