5

I have an array of

Expression<Func<MyClass,bool>>

However, I want to AND them all together to get just a single item of that type. How do I do this? Can I cast the result of Expression.And?

Brannon
  • 5,324
  • 4
  • 35
  • 83

1 Answers1

5

If you use the following extension method:

public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
{
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}

From here: http://www.albahari.com/nutshell/predicatebuilder.aspx

Then you can just write this to fold them all down to one expression.

public Expression<Func<T, bool>> AggregateAnd(Expression<Func<T,bool>>[] input)
{
    return input.Aggregate((l,r) => l.And(r));
}
yamen
  • 15,390
  • 3
  • 42
  • 52
  • It ends up that the above code won't actually work for most purposes because Invoke cannot be translated to SQL. I ended finding similar but more compatible code here: http://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-m – Brannon May 08 '12 at 19:38