Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a Linq IQueryable has an order by applied

Is there any way to find out if an IQueryable object has an OrderBy applied within its expression tree?

The scenario I have is that a grid control has paging enabled, and sorting per column. However there is not a sort applied by default, so in this case Linq to SQL does a horribly huge select for the row count, so in all scenarios I need to provide an order by, however I should only apply a default order by primary key if no other order has been specified.

So is this possible?

like image 986
Grofit Avatar asked Jul 17 '13 10:07

Grofit


People also ask

Can I order an IQueryable by a string?

Here we’ll create our own simplified extension method that allows you to order an IQueryable by a string using a similar method to Dynamic LINQ. It’s nowhere near as complete as Dynamic LINQ but it’s enough to demonstrate the idea behind the magic.

How do I add an “orderby” clause to an IQueryable?

First we get the underlying expression for the IQueryable, we need to modify this expression to tack an “OrderBy” clause on the end. You can think of this expression as the current definition of the IQueryable which we are going to modify. Next we specify a call to either “OrderBy” or “OrderByDescending” using our property selector from step 2.

How do I order my LINQ queries?

Reference System.Dynamic.Linq and then you can order your LINQ queries like this using (var ctx = new Entities ()) { return ctx.Items .Where (...some expression...) .OrderBy ("SomeProperty") ....

What is the expected query behavior of IQueryable<tsource>?

The query behavior that occurs as a result of executing an expression tree that represents calling Any<TSource> (IQueryable<TSource>) depends on the implementation of the type of the source parameter. The expected behavior is that it determines if source contains any elements.


1 Answers

You can find out by inspecting the expression tree of the query using a custom ExpressionVisitor or any recursive traversal mechanism of your choice.

I sense that your code is not well designed. You probably should just store that fact that ordering has been applied somewhere as a bool. Maybe the information flow of your app needs to be rearchitected.

With this inspection approach you are recovering this information in a hackish way.

like image 163
usr Avatar answered Sep 22 '22 12:09

usr