I have the following linq query (applies to Northwind database)
(from od in OrderDetails
where od.ProductID == 11 || od.ProductID == 42
select od.OrderID).Distinct()
What gives me a list of order identifiers (67 items) in which the order includes product 11 or 42. How can I rewrite the request to give me a list of order identifiers in which the order includes both product 11 and 42 ? The resulting list should contain only one order (orderid = 10248)
Obviously, the following query does not return any orders.
(from od in OrderDetails
where od.ProductID == 11 && od.ProductID == 42
select od.OrderID).Distinct()
Here is the sql query that does the job, but the best (or most efficient) way to write it to linq?
SELECT DISTINCT OrderID
FROM [Order Details]
WHERE (OrderID IN
(SELECT OrderID
FROM [Order Details] AS OD1
WHERE (ProductID = 11))) AND (OrderID IN
(SELECT OrderID
FROM [Order Details] AS OD2
WHERE (ProductID = 42)))
[edit]
. ( PredicateBuilder), , where . , - .
public static Expression<Func<Order, bool>> WhereProductIdListEqualsAnd( int[] productIds )
{
var condition = PredicateBuilder.True<Order>();
foreach ( var id in productIds )
{
condition = condition.And( o => o.OrderDetails.Any( od => od.ProductId == id ) );
}
return condition;
}