how do I combine Expression<Func<MyClass,bool>>[]?

对着背影说爱祢 提交于 2019-12-10 05:15:11

问题


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?


回答1:


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));
}


来源:https://stackoverflow.com/questions/10390784/how-do-i-combine-expressionfuncmyclass-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!