2

Is there a way to clear an IQueryable from its ordeyby clauses?

For example, we have a function that returns an ordered query:

public IQueryable<SomeType> GetOrderedQuery() 
{ 
   var query = from item in db.itemsTable
               where item.x != null 
               orderby item.y, item.z
               select item;
   return query;
}

And we have another function that needs to use the same query, but it needs to have it unordered:

public IQueryable<SomeType> GetUnorderedQuery() 
{ 
   var query = GetOrderedQuery();
   query.RemoveOrders(); // How to implement a RemoveOrders function?
   return query;
}

How can a RemoveOrders function be implemented? (Doesn't matter if as an extension method or not)

OfirD
  • 9,442
  • 5
  • 47
  • 90
  • try this library : https://github.com/MercedeX/GenericDataManager – Ehsan Sajjad Mar 20 '18 at 12:02
  • 2
    Just order it when it needs to be ordered; so there is no need to "unorder" it. – Sebastian Hofmann Mar 20 '18 at 12:04
  • Is it a problem that it is ordered? Maybe because of processing speed? – Harald Coppoolse Mar 20 '18 at 12:06
  • @john, you mean why would I want it? Mainly for a code reuse. consider the following use-case: I have website that displays a searchable, sortable grid of `item` records. The grid loads up with some predefined order, but when the client wants to sort upon some specific column, the initial order should be removed. – OfirD Mar 20 '18 at 12:07
  • So, instead of taking the ordered list and trying to unorder it, what is preventing you from taking the unordered list and ordering it? That's what I don't understand. – ProgrammingLlama Mar 20 '18 at 12:08
  • @john, that's certainly an option, but I wanted to know if I have another one – OfirD Mar 20 '18 at 12:11
  • 1
    Remember: [KISS](https://stackoverflow.com/questions/25999724/whats-the-difference-between-principles-yagni-and-kiss). – ProgrammingLlama Mar 20 '18 at 12:11

1 Answers1

8

If you don't want it ordered; don't order it. There's no robust way to walk back through an IQueryable<T> to get earlier states, let alone remove individual bits out of the middle. I suspect you want two queries:

public IQueryable<SomeType> GetUnorderedQuery()
    => db.itemsTable.Where(item => item.x != null);

public IOrderedQueryable<SomeType> GetOrderedQuery()
    => GetUnorderedQuery().OrderBy(item => item.y).ThenBy(item => item.z);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900