在 foreach 循环中使用 predicatebuilder 时出现问题
我在 foreach 循环中构建谓词时遇到问题。包含枚举器当前所在值的变量是我需要放入谓词中的变量。
所以,
IQueryable query = getIQueryableSomehow();
Predicate = PredicateBuilder.False<SomeType>();
foreach (SomeOtherType t in inputEnumerable)
{
Predicate = Predicate.Or( x => x.ListInSomeType.Contains(t) )
}
var results = query.Where(Predicate);
让我失望了。 Predicate 中进行 OR 运算的表达式基本上都使用来自 inputEnumerable 的相同 t,当然,我希望每个表达式进行 OR 运算到 Predicate 时使用来自 inputEnumerable 的不同 t。
我在循环后查看了调试器中的谓词,它位于看起来像 IL 的内容中。无论如何,其中的每个 lambda 看起来都完全相同。
谁能告诉我我在这里可能做错了什么?
谢谢,
艾萨克
I'm having trouble building predicates in a foreach loop. The variable that contains the value the enumerator is currently on is something I need to put in the predicate.
So,
IQueryable query = getIQueryableSomehow();
Predicate = PredicateBuilder.False<SomeType>();
foreach (SomeOtherType t in inputEnumerable)
{
Predicate = Predicate.Or( x => x.ListInSomeType.Contains(t) )
}
var results = query.Where(Predicate);
is failing me. The expressions ORed together in Predicate basically all use the same t from inputEnumerable, when of course I want each expression ORed into Predicate to use a different t from inputEnumerable.
I looked at the predicate in the debugger after the loop and it is in what looks like IL. Anyways each lambda in there looks exactly the same.
Can anyone tell me what I might be doing wrong here?
Thanks,
Isaac
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于闭包是如何工作的。您必须在本地复制 SomeOtherType t 实例,例如:
有关更多信息,请参阅: C# 循环中捕获的变量
The problem is how closures work. You have to copy the SomeOtherType t instance in a local like:
For more information, please see: Captured variable in a loop in C#
您关闭循环变量。为您的
SomeOtherType
声明一个局部变量,并在谓词中使用它。You're closing over the loop variable. Declare a local variable for your
SomeOtherType
and use that in your predicate.