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

本文是小编为大家收集整理的关于如何在一个循环中建立一个动态的linq表达式树的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

给定以下字符串数组:

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

我想在 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;

我知道如何从数组中提取值,所以这不是问题,但更重要的是如何在 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?
}

推荐答案

像这样:

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 子句,但它是等价的.如果你真的想要,你可以分解它.)

注意返回给 query 的赋值——像 Where 这样的方法返回一个 new 查询,这是将操作应用于 existing 查询的结果;它们不会更改现有查询中的任何内容.

本文地址:https://www.itbaoku.cn/post/1556958.html

问题描述

Given the following string arrray:

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

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;

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

推荐答案

Like this:

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

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

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.