组合Lambda表达式时出错:"变量' foo'类型' Foo'引用范围'',但未定义

时间:2018-05-30 13:13:38

标签: c# linq lambda linq-expressions

我试图combine two lambda expressions使用OR子句构建内容,但它失败并显示以下异常消息:

  

变量' foo'类型' Foo'引用范围'',但未定义。

为什么,以及如何解决?

这是一个失败的代码示例,基于上面链接的问题的Marc Gravell's answer

static Expression<Func<T, bool>> Or<T>(Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
    => Expression.Lambda<Func<T, bool>>(Expression.OrElse(a.Body, b.Body), b.Parameters);

static Expression<Func<Foo, bool>> BarMatches(Bar bar) => foo => foo.Bar.Value == bar.Value;
static Expression<Func<Foo, bool>> BazMatches(Baz baz) => foo => foo.Baz.Value == baz.Value;

// sample usage (see below): foos.Where(Or(MatchesBar(bar), MatchesBaz(baz)))

void Main()
{
    var foos = new[]
    {
        new Foo
        {
            Bar = new Bar
            {
                Value = "bar"
            },
            Baz = new Baz
            {
                Value = "baz"
            }
        },
        new Foo
        {
            Bar = new Bar
            {
                Value = "not matching"
            },
            Baz = new Baz
            {
                Value = "baz"
            }
        }
    }.AsQueryable();

    var bar = new Bar { Value = "bar" };
    var baz = new Baz { Value = "baz" };

    Console.WriteLine(foos.Where(Or(BarMatches(bar), BazMatches(baz))).Count());
}


// Define other methods and classes here
class Foo
{
    public Bar Bar { get; set; }
    public Baz Baz { get; set; }
}

class Bar
{
    public string Value { get; set; }
}

class Baz
{
    public string Value { get; set; }
}

1 个答案:

答案 0 :(得分:0)

问题是fooBarMatches的参数(BazMatches)不同。因此,您需要统一参数,以便Or-ed表达式使用相同的参数。这可以通过表达式替换器(从this answer中窃取)来完成:

static TExpr ReplaceExpressions<TExpr>(TExpr expression,
                                              Expression orig,
                                              Expression replacement)
where TExpr : Expression 
{
    var replacer = new ExpressionReplacer(orig, replacement);
    return replacer.VisitAndConvert(expression, "ReplaceExpressions");
}

private class ExpressionReplacer : ExpressionVisitor
{
    private readonly Expression From;
    private readonly Expression To;

    public ExpressionReplacer(Expression from, Expression to) {
        From = from;
        To = to;
    }

    public override Expression Visit(Expression node) {
        if (node == From) {
            return To;
        }
        return base.Visit(node);
    }
}

此类将一个表达式的所有实例替换为另一个表达式。我们现在可以使用它来创建统一表达式:

static Expression<Func<T, bool>> Or<T>(Expression<Func<T, bool>> a, Expression<Func<T, bool>> b) {
    // We know Parameters is exactly of length 1.
    // If you had multiple parameters you would need to invoke this for each parameter
    var replaced = ReplaceExpressions(a.Body, a.Parameters[0], b.Parameters[0]);
    return Expression.Lambda<Func<T, bool>>(Expression.OrElse(replaced, b.Body), b.Parameters);
}

虽然此代码可以满足您的需求,但我建议使用可以执行此操作的库以及更多内容:LinqKIT