Combine And/Or with PredicateBuilder?

╄→гoц情女王★ 提交于 2020-01-07 03:39:09

问题


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. 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:

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++;
      }
   }

回答1:


This works with a local copy of PredicateBuilder (no entityFramework or LinkToSql available at work):

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


来源:https://stackoverflow.com/questions/16839169/combine-and-or-with-predicatebuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!