C # Predicate Builder with "NOT IN" functionality

With PredicateBuilder, how do I get functionality similar to SQL IN or NOT IN?

For example, I have a list of identifiers, and I want to select all people whose identifiers match or do not match identifiers.

The people matching function is pretty simple (although there may be a better way to do this)

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 individuals whose identifiers are not on the personID list.

+6
source share
4 answers

Ask De Morgan :

NOT (P OR Q) = (NOT P) AND (NOT Q)

For your code to generate the equivalent of the NOT IN clause, rewrite it as

 var predicate = PredicateBuilder.True<Person>() 

and

 predicate = predicate.And(e=>e.PersonID != temp); 
+3
source

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)); 

This LINQ statement creates an SQL NOT IN query.

+3
source

Is this what you want?

 var predicate = PredicateBuilder.True<Person>() foreach (int i in personIDs) { int temp = i; predicate = predicate.And(e => e.PersonID != temp); } return persons.Where(predicate); 
0
source

Without looking at the api ....

 var predicate = PredicateBuilder.True<Person>() foreach (int i in personIDs) { int temp = i; predicate = predicate.And(e=>e.PersonID != temp); } return persons.Where(predicate); 
0
source

Source: https://habr.com/ru/post/895651/


All Articles