[英]"OR" on-demand with Linq to Entities, how can i do it?
I have the following query that performs a "AND" on-demand:我有以下按需执行“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.
}
So, how can i do the same query but performing a "OR" on-demand (so that the query makes sense)?那么,我如何才能执行相同的查询但按需执行“OR”(以便查询有意义)?
You can use the facsimile of an IN
for LINQ:您可以使用
IN
的传真 LINQ:
var productCodeList = products.Select(p => p.Code).ToList();
query = query.Where(p => productCodeList.Contains(p.Code));
It's basically saying:它基本上是在说:
SELECT *
FROM products
WHERE code IN (<list_of_codes>)
Either use the Contains
method ad Brad and Joe wrote, or (when that's not possible) use the PredicateBuilder:要么使用 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.