我有以下查询执行" AND"点播:
var products = // Selecting a list of products in anywhere based in a filter...
foreach (var product in products)
{
query = query.Where(p => p.Code == product.Code); // with this way, this query make no sense because this happens in any scenario, never a code can be more than one code.
}
那么,我怎么能做同样的查询,但执行" OR"按需(以便查询有意义)?
答案 0 :(得分:4)
使用Contains:
var codes = products.Select(x => x.Code).ToArray();
query.Where(p => codes.Contains(p.Code));
答案 1 :(得分:4)
您可以将IN
的传真用于LINQ:
var productCodeList = products.Select(p => p.Code).ToList();
query = query.Where(p => productCodeList.Contains(p.Code));
基本上是说:
SELECT *
FROM products
WHERE code IN (<list_of_codes>)
答案 2 :(得分:3)
使用广告Brad和Joe写的Contains
方法,或者(当不可能的话)使用PredicateBuilder:
var predicate = PredicateBuilder.False<Product>();
foreach (var product in products)
{
var code = product.Code;
predicate = predicate.Or(p => p.Code == code);
}
var products dataContext.Products.Where(predicate);