Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Predicate Builder with "NOT IN" functionality

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.

like image 448
Craig G. Avatar asked Aug 23 '11 05:08

Craig G.


2 Answers

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);
like image 145
devio Avatar answered Sep 25 '22 14:09

devio


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.

like image 45
denyo85 Avatar answered Sep 24 '22 14:09

denyo85