Thursday, September 23, 2010

LINQ Epiphany

The other day while I was working on a side project I stumbled into the concept of using a reusable lambda expressions.  I was querying data that in some cases needed to have a common filter run against it. So at first I realized I could do something like this:

Expression<Func<Product, bool>> reusableExpression = x => x.Price > 100;

Now this is pretty cool but moving forward with this concept I realized this could be a return value of a method that you may or may not pass parameters to.  This would allow for a reusable conditional lambda expression.  Example:

private Expression<Func<Product, bool>> ConditionalLambdaExpression(bool someVariable)
{
    if (someVariable)
    {
        return x => x.Price > 100;
    }
    return x => x.Price < 100;
}

This opened many doors for me in regards to simplifying many methods.  Now the one thing I did run into is you can only use this expression using the LINQ method syntax.  For example this will work:

var a = products.Where(ConditionalLambdaExpression(true));

And this will not:

var b = from p in products
        where ConditionalLambdaExpression(true)
        select p;

Although if you prefer to use the syntax above you could do this:

var b = from p in products.Where(ConditionalLambdaExpression(true))
        where p.Name == "Test"
        select p;