问题描述
给定以下字符串数组:
string[] ranges = new string[]{"0-100", "100-200", "500-1000"};
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 查询的结果;它们不会更改现有查询中的任何内容.
问题描述
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.