7

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?

Grofit
  • 17,693
  • 24
  • 96
  • 176
  • 1
    Only way I can think of is to do an orderby and see if the order is the same, or set a boolean when ordering, edit a shorter way may be to compare elements to see if theyre ordered – Sayse Jul 17 '13 at 10:30
  • In what way would the orderby(id) help the huge select? – usr Jul 17 '13 at 10:33
  • @usr Linq2Sql will use ALL COLUMNS in its `SELECT ROW_NUMBER() OVER (ORDER BY – Grofit Jul 17 '13 at 11:06
  • 2
    Can you not use `typeof(IOrderedQueryable).IsAssignableFrom(myQueryable.Expression.Type)` as suggested in http://stackoverflow.com/questions/5071426/how-can-i-tell-if-an-iqueryable-is-an-iorderedqueryable ? – Dejan Jun 30 '15 at 12:48
  • @Grofit you should see this answer http://stackoverflow.com/questions/36923850/how-to-know-if-orderby-was-applied-to-query – yosbel Apr 28 '16 at 20:25

1 Answers1

6

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Oh yes there is no doubt in my mind this is badly designed code, unfortunately as I am constrained by my clients technology choices from the prehistoric times I am limited in my choices to solve the underlying problem, and the grid control *can* have a default sort applied, but someone may turn the sorting off anyway which would cause problems so working on the underlying query (as it goes through a common interface for processing before being used by the grid). – Grofit Jul 17 '13 at 10:56