结合和/或predicateBuilder? [英] Combine And/Or with PredicateBuilder?

查看:145
本文介绍了结合和/或predicateBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 IDS 的名单,我只想做一个放在了第一位,并与在随后的。在过去,我已经养了柜台变量,当柜台是1,我做的,但在那之后我做了一个,但我很好奇,如果有一个更简单的方法:

 的foreach(IDS中的字符串ID)
{
   predicate.And(X => id.Contains(x.id)); //我只想在第一个ID做一个和。
}
 

这是我在过去所做的那样,但有一个更简洁的方式:

  INT计数器= 1;
的foreach(在IDS变种标识)
{
     字符串我= ID;
     如果(计数器== 1)
     {
         predicate = predicate.And(X => i.Contains(x.id));
         反++;
      }
      其他
      {
           predicate = predicate.Or(X => i.Contains(x.id));
          反++;
      }
   }
 

解决方案

该作品的predicateBuilder(没有的EntityFramework或LinkToSql可在工作)的本地副本:

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

的foreach(在ids.Skip串号(1))
{
    VAR LOCALID = ID; //获得的改性闭合否则
    predicate.Or(X => localID.Contains(x.id));
}
 

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

解决方案

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

这篇关于结合和/或predicateBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆