"OR" on-demand with Linq to Entities, how can i do it?

Go To StackoverFlow.com


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)?

2012-04-04 18:20
by Vinicius Ottoni


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:

FROM     products
WHERE    code IN (<list_of_codes>)
2012-04-04 18:24
by Brad Christie


Using Contains:

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

query.Where(p => codes.Contains(p.Code));
2012-04-04 18:23
by Joe
I got the following error: 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
What is Product.Code? A Class - Joe 2012-04-04 18:33
Nope. The prolem (i guess) is when you do the Select in products inside the where, the linq try to use the class product to perform the query. So, to solve it you have to perform the products.Select like @BradChristie did in his answer - Vinicius Ottoni 2012-04-04 18:39
Steven edit your answer with the right code now - Vinicius Ottoni 2012-04-04 18:41


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);
2012-04-04 18:27
by Steven
+1 for PredicateBuilder, though I prefer the version by Pete Montgomery - http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder - Jesse Squire 2012-04-04 18:38