How can I combine the expression <Func <MyClass, bool >> []?

I have an array

Expression<Func<MyClass,bool>>

However, I want them all to be together to get only one element of this type. How should I do it? Can I use the result of an Expression.And expression?

+5
source share
1 answer

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 simply write this to collapse all up to one expression.

public Expression<Func<T, bool>> AggregateAnd(Expression<Func<T,bool>>[] input)
{
    return input.Aggregate((l,r) => l.And(r));
}
+5
source

Source: https://habr.com/ru/post/1532906/


All Articles