如何在循环中构建动态linq表达式树

Fix*_*xer 1 c# linq

给出以下字符串arrray:

string[] ranges = new string[]{"0-100", "100-200", "500-1000"};
Run Code Online (Sandbox Code Playgroud)

我想在linq表达式中动态表达这一点 - 有点像:

var query = from p in Db.Products()
            where p.Amount() >= 0
            where p.Amount() <= 100
            where p.Amount() >= 101
            where p.Amount() <= 200
            where p.Amount() >= 500
            where p.Amount() <= 1000
            select p;
Run Code Online (Sandbox Code Playgroud)

我知道如何从数组中提取值,这不是问题,但更多的是如何在for循环中动态构建linq表达式:

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

foreach (var item in ranges)
{
    int min = int.Parse(item.Split('-').First());
    int max = int.Parse(item.Split('-').Last());                
    //Linq expression?
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

像这样:

IQueryable<Product> query = DB.Products();
foreach (var item in ranges)
{
    int min = int.Parse(item.Split('-').First());
    int max = int.Parse(item.Split('-').Last());                
    query = query.Where(p => p.Amount() >= min && p.Amount() <= max);
}
Run Code Online (Sandbox Code Playgroud)

(我只有你所拥有的where子句的一半,但它是等价的.如果你真的想要,你可以分解它.)

请注意返回的分配query- Where返回查询的方法,这是将操作应用于现有查询的结果; 它们不会更改现有查询中的任何内容.