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

I have a 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 returns what I expect, but if I have PredicateBuilder.False<Value>() , it returns 0 records. Can someone explain what the difference is and why in one scenario I return 0 records, and in the other I get what I expect. I already read the PredicateBuilder documentation, but that was a bit confusing. I feel this is due to the fact that I'm predicting Anding together?

+7
source share
2 answers

When using PredicateBuilder to gradually create a predicate from 0 or more conditions, it’s convenient to start with a β€œneutral” predicate, which you can add to, because you can simply iterate over the conditions and and or or them together with the latter. For example.

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

This will be equivalent to simpler logic:

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

What would be equivalent

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

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

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

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

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

+1
source

How it works True and False methods do nothing special: they are just convenient keyboard shortcuts for creating Expression>, which is initially evaluated as true or false. So the following:

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

Expression> predicate = c => true; When you create a predicate by multiple styling and / or conditions, it is useful to have a starting point of either true or false (respectively).

Information completed http://www.albahari.com/nutshell/predicatebuilder.aspx

-one
source

All Articles