PredicateBuilder: How to negate a predicate?

Posts   
 
    
D-Rider
User
Posts: 11
Joined: 09-Nov-2006
# Posted on: 15-Mar-2010 22:00:55   

I'm using the LLBL version of predicate builder (thank you so much for this Frans!) to build dynamic linq queries. I've hit a case where it would be quite convenient to have a way to negate the predicate. It seemed like this would be easy, but after reading the threads on the forum, the Expression class help info, and various StackOverflow posts, I think I'm way over my head in trying to do this.

I could, of course, do it another way, but it basically requires checking a negate flag, and building my predicates differently in that case. I was hoping there would be a simple solution to this.

Any help would be appreciated, even if it's just a definitive statement that it can't be done, so I don't waste any more time trying to do it. simple_smile

Thanks

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 16-Mar-2010 04:29:31   

Hi there,

Please add this method to PredicateBuilder class:

public static Expression<Func<T, bool>> Negate<T>(this Expression<Func<T, bool>> expr1)
{
    return Expression.Lambda<Func<T, bool>>
         (Expression.Not(expr1.Body), expr1.Parameters);
}

Usage:

var predicate = PredicateBuilder.Null<CustomersEntity>();
predicate = predicate.Or(c => c.Country == "USA");
predicate = predicate.Or(c => c.City == "London");
...
predicate = predicate.Negate();
David Elizondo | LLBLGen Support Team
D-Rider
User
Posts: 11
Joined: 09-Nov-2006
# Posted on: 16-Mar-2010 15:10:59   

Thank you!

And thanks as always for the prompt and excellent support.