Is it possible to pass parts of a linq Query into a function? I want create a common interface for my DAL that always uses the same query interface. For example,
List<T> Get(Join j, Where w, Select s){ return currentDataContext<T>.Join(j).Where(w).Select(s).ToList(); }
Is this sort of thing possible? I’m thinking it would be done with expression trees, but I haven’t been able to find examples of it.
Well, the ‘join’ is tricky, because it is very hard to express a join – but things like where / select / orderby are pretty easy…
Really, it is just a case of combining the various LINQ methods on
IQueryable<T>, which generally acceptExpression<Func<...>>for some combination. So a basic select with an optional predicate would be:I would tend to return
IQueryable<T>too, since that is fully composable. If the caller wants a list, they can always useToList()on it… or (for example):which (using Northwind) does the query:
The problem with including the ‘select’ (projection) in the query is that you would end up with multiple generic types. Since you often want the projection the be an anonymous type, it would then be pretty impossible to specify the projection type (anonymous) and the table-type, and it would not be callable.
In reality, I wonder if there is much benefit writing such a method at all. I might just stick with a base method:
And let the caller compose it in their preferred way – perhaps with query syntax:
Which uses:
Alternatively, if you really do want to include the order by and projection, then an extension method is the most practical approach; then you don’t need to specify the original (source) T (which is what makes it uncallable when mixed with anon-types):
Then consider a DAL method such as:
Which uses (again, with Northwind):