2

我有以下按需执行“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”(以便查询有意义)?

4

3 回答 3

4

使用包含

var codes = products.Select(x => x.Code).ToArray();

query.Where(p => codes.Contains(p.Code));
于 2012-04-04T18:23:03.073 回答
4

您可以使用INfor 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>)
于 2012-04-04T18:24:01.563 回答
3

要么使用ContainsBrad 和 Joe 所写的方法,要么(如果不可能)使用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);
于 2012-04-04T18:27:29.283 回答