如何在循环中构建动态AND或LINQ表达式树

如何在循环中构建动态AND或LINQ表达式树

本文介绍了如何在循环中构建动态AND或LINQ表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接着上一个问题,我现在正试图弄清楚如何为AND& amp; OR查询.

Following on from a previous question i asked, I'm now trying to figure out how to build dynamic expressions for both AND & OR queries.

给出以下字符串数组:

string[] ranges = new string[]{"0-100", "100-200", "500-1000"};

我想在linq表达式中动态表达这一点-类似以下内容:

I would like to dynamically express this in a linq expression - Something along the lines of:

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表达式?

How do i dynamically build the linq expression in this loop?

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的布尔状态开始,而or一起在循环中谓词.相反,可以将状态trueand连同谓词一起开始.

Notice how we start with the boolean state of false, and or together predicates in the loop. Conversely, you can start with a state of true and and together the predicates.

最后,不确定查询理解语法是否可行,但是最终查询如下:

Finally, not sure if this is possible with query comprehension syntax, but your ultimate query can then look like:

var v = products.Where(predicate);

这篇关于如何在循环中构建动态AND或LINQ表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:35