gpt4 book ai didi

c# - AndAlso 之间有几个 Expression> : referenced from scope

转载 作者:太空狗 更新时间:2023-10-29 21:09:38 26 4
gpt4 key购买 nike

我有 3 个谓词,我想做一个 AndAlso之间。我在开发板上找到了几个示例,但无法解决我的问题。

这些谓词是:Expression<Func<T, bool>>

我有这段代码:

Expression<Func<T, bool>> predicate1 = ......;
Expression<Func<T, bool>> predicate2 = ......;
Expression<Func<T, bool>> predicate3 = ......;

我创建了一个扩展方法来制作“AndAlso”:

public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr,
Expression<Func<T, bool>> exprAdd)
{
var param = Expression.Parameter(typeof(T), "p");
var predicateBody = Expression.AndAlso(expr.Body, exprAdd.Body);
return Expression.Lambda<Func<T, bool>>(predicateBody, param);

//Tried this too
//var body = Expression.AndAlso(expr.Body, exprAdd.Body);
//return Expression.Lambda<Func<T, bool>>(body, expr.Parameters[0]);
}

我是这样使用的:

var finalPredicate = predicate1
.AndAlso<MyClass>(predicate2)
.AndAlso<MyClass>(predicate3);

谓词看起来是这样的: enter image description here

当我在查询中使用时:

var res =  myListAsQueryable().Where(finalPredicate).ToList<MyClass>();

我得到这个错误:从范围“”引用了类型为“BuilderPredicate.MyClass”的变量“p”,但未定义

你能告诉我哪里出了问题吗?

非常感谢,

最佳答案

问题在于创建一个新参数 - 您可以这样做,但如果您只是将其分配给最终的 lambda,则您的参数与提供的表达式中的原始参数之间没有任何联系。尝试更改表达式的参数名称,然后检查 finalPredicate。你会看到类似这样的东西:

{p => (((x.Age == 42) AndAlso (y.Salary == 50)) AndAlso z.FirstName.StartsWith("foo"))}

现在问题应该很明显了。

Marc Gravell 在 this answer 中提出建议 一个通用的 Expression.AndAlso,这正是您所需要的:

public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
// need to detect whether they use the same
// parameter instance; if not, they need fixing
ParameterExpression param = expr1.Parameters[0];
if (ReferenceEquals(param, expr2.Parameters[0]))
{
// simple version
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(expr1.Body, expr2.Body), param);
}
// otherwise, keep expr1 "as is" and invoke expr2
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
Expression.Invoke(expr2, param)), param);
}

(马克的代码,不是我)

关于c# - AndAlso 之间有几个 Expression<Func<T, bool>> : referenced from scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13967523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com