Suppose I have an IQueryable<T>
expression that I'd like to encapsulate the definition of, store it and reuse it or embed it in a larger query later. For example:
IQueryable<Foo> myQuery =
from foo in blah.Foos
where foo.Bar == bar
select foo;
Now I believe that I can just keep that myQuery object around and use it like I described. But some things I'm not sure about:
How best to parameterize it? Initially I've defined this in a method and then returned the
IQueryable<T>
as the result of the method. This way I can defineblah
andbar
as method arguments and I guess it just creates a newIQueryable<T>
each time. Is this the best way to encapsulate the logic of anIQueryable<T>
? Are there other ways?What if my query resolves to a scalar rather than
IQueryable
? For instance, what if I want this query to be exactly as shown but append.Any()
to just let me know if there were any results that matched? If I add the(...).Any()
then the result isbool
and immediately executed, right? Is there a way to utilize theseQueryable
operators (Any
,SindleOrDefault
, etc.) without immediately executing? How does LINQ-to-SQL handle this?
Edit: Part 2 is really more about trying to understand what are the limitation differences between IQueryable<T>.Where(Expression<Func<T, bool>>)
vs. IQueryable<T>.Any(Expression<Func<T, bool>>)
. It seems as though the latter isn't as flexible when creating larger queries where the execution is to be delayed. The Where()
can be appended and then other constructs can be later appended and then finally executed. Since the Any()
returns a scalar value it sounds like it will immediately execute before the rest of the query can be built.