如何组合两个lambda表达式 [英] How to Combine two lambdas

查看:229
本文介绍了如何组合两个lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  结合两个兰巴EX pressions在C#

我有两个以下EX pressions:

I have two following expressions:

Expression<Func<string, bool>> expr1 = s => s.Length == 5;
Expression<Func<string, bool>> expr2 = s => s == "someString";

现在,我需要他们或合并。事情是这样的:

Now I need to combine them with OR. Something like this:

Expression.Or(expr1, expr2)

有没有什么办法,使这个类似于像上面code方式:

Is there any way to make this similar to above code way like:

expr1 || expr2

我明白在这个例子中我可以结合它摆在首位:

I understand in this example I can just combine it in the first place:

Expression<Func<string, bool>> expr = s => s.Length == 5 || s == "someString"

但我不能做到这一点在我真正的code,因为我得到表达式1和表达式2作为参数的方法。

but I can't do it in my real code as I get expr1 and expr2 as arguments to the method.

推荐答案

要完成Eric的答案,使用新的防爆pressionVisitor 在.NET 4中,而不是介绍自定义重写:

To complete Eric's answer, using the new ExpressionVisitor introduced in .NET 4 rather than a custom rewriter:

internal class ParameterReplacer : ExpressionVisitor {
    private readonly ParameterExpression _parameter;

    protected override Expression VisitParameter(ParameterExpression node) {
        return base.VisitParameter(_parameter);
    }

    internal ParameterReplacer(ParameterExpression parameter) {
        _parameter = parameter;
    }
}

class Program {

    static void Main(string[] args) {
        Expression<Func<string, bool>> expr1 = s => s.Length == 5;
        Expression<Func<string, bool>> expr2 = s => s == "someString";
        var paramExpr = Expression.Parameter(typeof(string));
        var exprBody = Expression.Or(expr1.Body, expr2.Body);
        exprBody = (BinaryExpression) new ParameterReplacer(paramExpr).Visit(exprBody);
        var finalExpr = Expression.Lambda<Func<string, bool>>(exprBody, paramExpr);
    }

}

这篇关于如何组合两个lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆