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 restOfPredicate
is 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
.
true && (x.value1 == "1") && (x.value2 == "2")
, which may or may not be evaluate totrue
, depending on your items (hence you get back "what you expect", whatever that is). If you start out fromfalse
, on the other hand, the expression can never evaluate totrue
, because andingfalse
results infalse
. Therefore, the predicate expression returnsfalse
for all items and you don't get back any results. – Tartarus