Check if a Linq IQueryable has an order by applied

c# expression-trees linq

Question

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?

1
7
7/17/2013 10:28:20 AM

Accepted Answer

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.

6
7/17/2013 10:34:38 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow