With PredicateBuilder how do I get functionality similar to the SQL IN or NOT IN query?
For example I have a list of IDs and I want to select all of the People whose IDs either Match or do not match the IDs.
The people match functionality is fairly straightforward (although there may be a better way to do it)
var predicate = PredicateBuilder.False<Person>()
foreach (int i in personIDs)
{
int temp = i;
predicate = predicate.Or(e=>e.PersonID == temp);
}
return persons.Where(predicate);
So how do I get the opposite? I want all persons whose IDs are not in the personIDs list.
Ask De Morgan:
NOT (P OR Q) = (NOT P) AND (NOT Q)
To have your code generate the equivalent of a NOT IN condition, rewrite as
var predicate = PredicateBuilder.True<Person>()
and
predicate = predicate.And(e=>e.PersonID != temp);
Do you use Entity Framework?
Then you can build the query without PredicateBuilder:
var personIds = new List<int>() { 8,9,10 };
var query = persons.Where(it => !personIds.Contains(it.PersonId));
From this LINQ statement a SQL NOT IN query is created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With