Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if an IQueryable is an IOrderedQueryable?

Tags:

c#

linq

I have an IQueryable. I have not called OrderBy on it or otherwise done anything with it.

If I do:

// for some reason, isItOrdered is always true
var isItOrdered = myQueryable is IOrderedQueryable<T>

Why is this always true? (It seems like it shouldn't be.) And, more importantly, how can I tell if an IQueryable already has been ordered? (i.e. is truly an IOrderedQueryable)

I would like to be able to do something like:

if (myQueryable is IOrderedQueryable<T>)
  myQueryable = myQueryable.ThenBy(...);
else
  myQueryable = myQueryable.OrderBy(...);
like image 248
Pedro Avatar asked Feb 21 '11 21:02

Pedro


People also ask

What is IOrderedQueryable?

The IOrderedQueryable<T> interface is intended for implementation by query providers. This interface represents the result of a sorting query that calls the method(s) OrderBy, OrderByDescending, ThenBy or ThenByDescending.

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider.

What is IQueryable return?

IQueryable is executed. // // Returns: // A System.Type that represents the type of the element(s) that are returned when. // the expression tree associated with this object is executed.


2 Answers

You haven't shown what's creating your queryable to start with, but perhaps it's naturally ordered in some way?

What you've got does check whether it's really an IOrderedQueryable<T> - I suspect that it's just that your query provider always provides an ordered queryable, even if the order isn't obvious.

EDIT: Okay, something else you might try:

if (typeof(IOrderedQueryable<T>).IsAssignableFrom(myQueryable.Expression.Type))

... or in general, print out myQueryable.Expression.Type and see what it looks like.

like image 51
Jon Skeet Avatar answered Sep 26 '22 01:09

Jon Skeet


This seems to work

if (query.Expression.Type == typeof(IOrderedQueryable<T>))
    myQueryable = myQueryable.ThenBy(...);
else
    myQueryable = myQueryable.OrderBy(...);
like image 27
John Avatar answered Sep 26 '22 01:09

John