Difference between PredicateBuilder<True> and PredicateBuilder<False>?

半城伤御伤魂 提交于 2020-08-24 05:32:10

问题


I have the code:

   var predicate = PredicateBuilder.True<Value>();

predicate = predicate.And(x => x.value1 == "1");
predicate = predicate.And(x => x.value2 == "2");

var vals = Value.AsExpandable().Where(predicate).ToList();

If I have PredicateBuilder.True<Value>(), it brings back what I expect, but if I have PredicateBuilder.False<Value>(), it brings back 0 records. Can someone explain what the the difference is and why in one scenario I get back 0 records an in the other I get what I expect. I already read the PredicateBuilder documenation, but it was a bit confusing. I have a feeling it has to do with the fact that I am Anding predicates together?


回答1:


When using PredicateBuilder to incrementally build a predicate of 0 or more conditions, it is convenient to start off with a "neutral" predicate that can be added to, since you can then just iterate through the conditions and either and or or them together wth the last one. E.g.

var predicate = PredicateBuilder.True<Value>();

foreach (var item in itemsToInclude) {
  predicate = predicate.And(o => o.Items.Contains(item));
}

This would be equivalent to the more straightforward boolean logic:

var predicate = true;

foreach (var item in itemsToInclude) {
  predicate = predicate && o.Items.Contains(item);
}

Which would be equivalent to

true && ((o.Items.Contains(itemsToInclude[0] && o.Items.Contains.itemsToInclude[1]) ...)

Or true && restOfPredicate, which evaluates to true if restOfPredicateis true, and false if restOfPredicate is false. Hence why it's considered neutral.

Starting out with PredicateBuilder.False, however, would be equivalent false && restOfPredicate, which would always evaluate to false.

Similarly for or, starting out with false would be equivalent to false || restOfPredicate, which evaluate to false if restOfPredicate is false and true if restOfPredicate is true. And true || restOfPredicate would always evaluate to true.

Bottom line: Use PredicateBuilder.True as a neutral starting point with PredicateBuilder.And, and PredicateBuilder.False with PredicateBuilder.Or.




回答2:


How it Works The True and False methods do nothing special: they are simply convenient shortcuts for creating an Expression> that initially evaluates to true or false. So the following:

var predicate = PredicateBuilder.True (); is just a shortcut for this:

Expression> predicate = c => true; When you’re building a predicate by repeatedly stacking and/or conditions, it’s useful to have a starting point of either true or false (respectively).

Info complete http://www.albahari.com/nutshell/predicatebuilder.aspx



来源:https://stackoverflow.com/questions/16695523/difference-between-predicatebuildertrue-and-predicatebuilderfalse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!