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?

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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why