tags:

views:

374

answers:

2

I like to reuse expressions for DRY reasons, but how do I reuse the expressions within a LINQ statement?

e.g.

I have

public static class MyExpressions {
    public static Expression<Func<Product,bool>> IsAGoodProduct() {
        return (p) => p.Quality>3;
    }
}

And would like to use that in LINQ statements, so

  var goodProds = from p in dataContext.Products
                  where ????? // how do I use IsAGoodProduct here?
                  select p;

Sure, I could use the IQueryableExtension.Where function, but that would make joins and other functions alot uglier for more complex queries.

Is this possible or is it a limitation of LINQ?

+10  A: 

If you move from the LINQ syntactic sugar it is possible:

var goodProds = dataContext.Products.Where(MyExpressions.IsAGoodProduct());

Without it, it isn't possible.

There's nothing to stop you mixing the two styles to build a single query though.

Example:

  var goodProds = from p in dataContext.Products
                                       .Where(MyExpressions.IsAGoodProduct())
                  group p by p.Category into g 
                  select new {Category = g.Key, ProductCount = g.Group.Count()};
Garry Shutler
@Gary -- hope you don't mind that I added an example to make it clearer.
tvanfosson
No, that's great :)
Garry Shutler
What about using: "where IsAGoodProduct().Compile().Invoke()"
Razzie
@Razzie, no that wouldn't work - firstly, it needs an *expression tree* (since it is a data-context) - not a delegate. Second, the invoke simply can't be used like that.
Marc Gravell
@Marc ok thanks, I tested it but with a List<T> and it worked there, so I wondered.
Razzie
A: 

By the way, I've come across this useful article which explains how you can create dynamic LINQ Queries that reference functions wrapped as Expressions using a custom ToExpandable() extension method. The solution provided can be used within the various parts of a LINQ Query all while preserving the use of comprehension syntax instead of resorting to lambda syntax.

jpierson