继从previous https://stackoverflow.com/questions/9718805/how-to-build-a-dynamic-linq-expression-tree-in-a-loop/9718896#9718896我问的问题,我现在正在尝试弄清楚如何为 AND 和 OR 查询构建动态表达式。
给定以下字符串数组:
string[] ranges = new string[]{"0-100", "100-200", "500-1000"};
我想用 linq 表达式动态地表达这一点 - 类似于:
var v = from p in products
where
(p.Amount >= 0 && p.Amount <= 100) ||
(p.Amount >= 101 && p.Amount <= 200) ||
(p.Amount >= 500 && p.Amount <= 1000)
select p;
如何在此循环中动态构建 linq 表达式?
string[] ranges = new string[]{"0-100", "100-200", "500-1000"};
var query = products.AsQueryable();
foreach (var item in ranges)
{
int min = int.Parse(item.Split('-').First());
int max = int.Parse(item.Split('-').Last());
//Linq expression?
}
Use 谓词构建器 http://www.albahari.com/nutshell/predicatebuilder.aspx:
string[] ranges = new string[]{"0-100", "100-200", "500-1000"};
var predicate = PredicateBuilder.False<Product>();
foreach (var item in ranges)
{
int min = int.Parse(item.Split('-').First());
int max = int.Parse(item.Split('-').Last());
predicate = predicate.Or(p => p.Amount >= min && p.Amount <= max);
}
注意我们如何从布尔状态开始false
, and or
循环中的谓词一起。相反,您可以从以下状态开始true
and and
将谓词放在一起。
最后,不确定查询理解语法是否可以实现这一点,但您的最终查询可能如下所示:
var v = products.Where(predicate);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)