Check if a Linq IQueryable has an order by applied

c#, expression-trees, linq

Solution

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.

Problem

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?

Original source

Related problems