Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether an IQueryable<T> has been ordered or not

Is there a way to know if an IQueryable<T> has been ordered (using OrderBy or OrderbyDescending)?

So I know whether to call OrderBy or ThenBy on the collection.

IQueryable<Contact> contacts = Database.GetContacts(); 

I tried contacts is IOrderedQueryable<Contact>, but it's always true.

Edit: I just changed my example, the previous one wasn't really showing my point. Assume that GetContacts uses Entity Framework and simply returns all the records of a table.

Later on, I apply several functions to contacts, I have no knowledge of what those functions do. They can sort or filter the IQueryable<Contact>.

When I get the collection back, I need to sort it once more. To do so, I need to know whether I need to call OrderBy, or ThenBy. So I don't reorder the whole collection if it has already been sorted.

like image 239
Bertrand Marron Avatar asked Dec 14 '11 16:12

Bertrand Marron


1 Answers

It's possible. Here's an extension method:

public static bool IsOrdered<T>(this IQueryable<T> queryable) {     if (queryable == null)     {         throw new ArgumentNullException("queryable");     }      return queryable.Expression.Type == typeof(IOrderedQueryable<T>); } 
like image 77
Zac Charles Avatar answered Oct 20 '22 06:10

Zac Charles