简体   繁体   English

结合和/或PredicateBuilder?

[英]Combine And/Or with PredicateBuilder?

I have a list of Ids and I only want to do an AND on the first one and and OR on the subsequent ones. 我有一个Ids列表,我只想对第一个进行AND OR ,然后对随后的AND OR In the past, I have kept a counter variable and when the counter is 1, I do the And , but after that I do an OR , but I was curious if there was an easier way: 过去,我保留一个counter变量,当counter为1时,我执行And ,但是之后执行OR ,但我想知道是否有更简单的方法:

foreach(string id in Ids)
{
   predicate.And(x=> id.Contains(x.id)); //I want to do an And only on the first id.
}

This is what I have done in the past, but is there a more concise way: 这是我过去所做的,但是还有更简洁的方法:

int counter = 1;
foreach (var Id in Ids)
{
     string i = Id;
     if (counter == 1)
     {
         predicate = predicate.And(x => i.Contains(x.id));
         counter++;
      }
      else
      {
           predicate = predicate.Or(x=>i.Contains(x.id));
          counter++;
      }
   }

This works with a local copy of PredicateBuilder (no entityFramework or LinkToSql available at work): 这可与PredicateBuilder的本地副本一起使用(工作时不可用entityFramework或LinkToSql):

var firstID = ids.First();
predicate.And(x => firstID.Contains(x.id));

foreach (string id in ids.Skip(1))
{
    var localID = id;   //access to a modified closure otherwise
    predicate.Or(x => localID.Contains(x.id)); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM