为什么使用 PredicateBuilder 的这段代码不起作用?
为什么我的列表没有返回任何内容?
class Program
{
static void Main(string[] args)
{
var list = new List<string>{ "apple" , "mango" , "chickoo", "kiwi" };
var searchWord = new List<string>{ "a" };
var predicate = PredicateBuilder.False<string>();
foreach(var word in searchWord)
{
predicate.Or(p => p.Contains(word));
}
var qry = list.Where(predicate.Compile());
foreach (var item in qry)
{
Console.WriteLine(item);
}
Console.Read();
}
}
我正在使用 Joseph Albahari 的 PredicateBuilder。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将结果分配给您的
predicate
变量:PredicateBuilder 页面还强调了一个重要问题:
因此,您的代码应类似于以下内容:
You need to assign the result to your
predicate
variable:The PredicateBuilder page also emphasizes an important issue:
Thus, your code should resemble this:
这里有两个问题:
Or
扩展方法不会改变现有的表达式树 - 它返回一个新的表达式树。表达式树通常是不可变的。尝试:
或者更好:
There are two issues here:
Or
extension-method does not mutate an existing expression-tree - it returns a new one. Expression-trees in general are immutable.Try:
Or even nicer:
这对我来说看起来不正确:
我怀疑它应该是:
换句话说,就像 LINQ 的其余部分一样,
PredicateBuilder
不允许您更改当前谓词- 它允许您基于现有谓词和新条件构建新谓词。无论如何,这肯定是 示例代码 所建议的......
当您查看完整的源代码时
PredicateBuilder
的代码(在同一页上),证实了这一点 - 谓词实际上只是一个Expression>
- 即表达式树。您没有创建PredicateBuilder
类或类似内容的实例。表达式树是不可变的,因此Or
唯一可以做的就是返回一个新的表达式树,如下所示:This doesn't look right to me:
I suspect it should be:
In other words, just like the rest of LINQ,
PredicateBuilder
doesn't let you change the current predicate - it lets you build a new predicate based on the existing one and a new condition.That's certainly what the sample code suggests, anyway...
When you look at the complete source code for
PredicateBuilder
(on the same page), that confirms it - the predicate is actually just anExpression<Func<T, bool>>
- i.e. an expression tree. You're not creating an instance of aPredicateBuilder
class or anything like that. Expression trees are immutable, so the only thingOr
can do is return a new expression tree, like this: