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(...);
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.
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.
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.
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.
This seems to work
if (query.Expression.Type == typeof(IOrderedQueryable<T>))
myQueryable = myQueryable.ThenBy(...);
else
myQueryable = myQueryable.OrderBy(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With