从 previous 开始我问的问题,我现在正试图弄清楚如何为 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?
}
最佳答案
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
的 bool 状态开始的,以及 or
循环中的谓词。相反,您可以从 true
状态和 and
谓词开始。
最后,不确定查询理解语法是否可行,但您的最终查询可能如下所示:
var v = products.Where(predicate);
关于c# - 如何在循环中构建动态 AND OR linq 表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9722171/