本文介绍了连接多个凡在LINQ的条款或替代和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
反正是有加入LINQ where子句作为OR?
VAR整数=新[] {1,3,5 7};
VAR的查询=从我在整数选择我;
=查询query.Where(Q =>问== 3);
=查询query..Where(Q =>问== 7);
我要的是动态地添加where子句,但让他们使用或代替和能力p>
解决方案
如果你想留你的强类型的LINQ查询你应该看看LinqKit和谓语的建设。我已经使用这个类似的东西,发现它与和/或过滤器堆叠很好地工作。
检查出的获得更深入的信息。下面是从我的代码剪断:
//设置初始谓词的obj然后堆在别人:
basePredicate = basePredicate.And(p =>假);
VAR predicate1 = PredicateBuilder.True<&人GT;();
的foreach(在PARMS SearchParms PARM)
{
开关(parm.field)
{
案名字:
predicate1 = predicate1.And(p值=> p.FirstName.Trim()ToLower将()包含(S值)。);
中断;
//等等......
}
}
//运行基于您和/或PARM值的键来确定堆叠:
如果(Parm.isAnd){
basePredicate = basePredicate.And(predicate1);
}其他{
basePredicate = basePredicate.Or(predicate1);
}
Is there anyway to join LINQ where clauses as OR ?
var ints = new [] { 1, 3, 5, 7 };
var query = from i in ints select i;
query = query.Where (q => q == 3);
query = query..Where (q => q == 7);
What I want is the ability to dynamically add where clauses but make them use OR instead of AND
解决方案
If you want to stay with your strong-typing Linq queries you should look into LinqKit and predicate building. I have used this for something similar and found it to work well with And / Or stacking of filters.
Check out the C#4.0/3.0 in a Nutshell excerpt for more in depth info. Here is a snip from my code:
//Setup the initial predicate obj then stack on others:
basePredicate = basePredicate.And(p => false);
var predicate1 = PredicateBuilder.True<Person>();
foreach (SearchParms parm in parms)
{
switch (parm.field)
{
case "firstname":
predicate1 = predicate1.And(p => p.FirstName.Trim().ToLower().Contains(sValue));
break;
//etc...
}
}
//Run a switch based on your and/or parm value to determine stacking:
if (Parm.isAnd) {
basePredicate = basePredicate.And(predicate1);
} else {
basePredicate = basePredicate.Or(predicate1);
}
这篇关于连接多个凡在LINQ的条款或替代和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!