LINQ PredicateBuilder (A or B) And ( X or Y) expression error

Simple way to work with two predicate builder with And/Or statements are as – 


// This predicate is the 1st predicate builder
var predicate = PredicateBuilder.True<Widget>();

// and I am adding more predicates to it (all no problem here)
predicate = predicate.And(c => c.ColumnA == 1);
predicate = predicate.And(c => c.ColumnB > 32);
predicate = predicate.And(c => c.ColumnC == 73);

// Now I want to add another AND predicate with is actually comprises 
// of sub OR predicates
if(keywords.Length > 0)
    // NOTICE HERE: Here I am starting off a brand new 2nd predicate builder....
    // (not ANDing it to the existing one (yet))
    var subpredicate = PredicateBuilder.False<Widget>();

    foreach(string s in keywords)
        string t = s;
        subpredicate = subpredicate.Or(c => c.Name.Contains(t));

    // This is the "gotcha" bit... adding the ANDing the independent
    // sub-predicate to the 1st one....

    // If done like this, you will FAIL!
//  predicate = predicate.And(subpredicate); // FAIL at runtime!

    // To correct it, you must do this...
    predicate = predicate.And(subpredicate.Expand());  // OK at runtime!

One thought on “LINQ PredicateBuilder (A or B) And ( X or Y) expression error

  1. What libraries are you ‘using’ to access the Expand() method?

    I ran into this same problem last year. I found an implementation of Predicate Builder that handled nested expressions, but it doesn’t support Expand(). I looked at LinqKit, but the subexpression syntax isn’t compatible with the code I already have in production. The part I’m missing is the expand method which I think is now supported in the .Net framework, but I don’t know which library to reference.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s