开发者

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.


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜