Search code examples
c#sql-order-byiqueryable

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.


Solution

  • Short answer is no, the Queryable class doesn't maintain a flag or whether the collection is sorted nor what method may have been used to perform such a sort.

    http://msdn.microsoft.com/en-us/library/system.linq.queryable.aspx