I have the following query that performs a "AND" on-demand:
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)?
You can use the facsimile of an IN
for 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>)
Using Contains:
var codes = products.Select(x => x.Code).ToArray();
query.Where(p => codes.Contains(p.Code));
Either use the Contains
method ad Brad and Joe wrote, or (when that's not possible) use the 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);
Unable to create a constant value of type 'MyEntities.Product'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Vinicius Ottoni 2012-04-04 18:31