如何在循环中构建动态linq表达式树 [英] How to build a dynamic linq expression tree in a loop

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

问题描述

给出以下字符串错误:

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 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;

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

I know how to extract the values from the array so that's not the issue, but more so how do i dynamically build the linq expression in a for loop:

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?
}

推荐答案

像这样:

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);
}

(我只有where子句的一半,但它是等效的.如果您确实需要,可以将其分解.)

(I've only got half the where clauses you had, but it's equivalent. You can break it up if you really want.)

注意将分配返回给query-类似Where的方法返回一个 new 查询,这是对该操作应用到 existing 查询的结果;他们不会更改现有查询中的任何内容.

Note the assignment back to query - methods like Where return a new query which is the result of applying the operation to the existing query; they don't change anything in the existing query.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆