Linq to Sql with operator A in one field

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;
}
+3
2

:

var result = Orders.Where(o => o.OrderDetails.Any(od => od.ProductId == 11) 
                            && o.OrderDetails.Any(od => od.ProductId == 42));
+3

, :

var o1 = OrderDetails.Where( od => od.ProductID == 11).Select( od => od.OrderID );
var o2 = OrderDetails.Where( od => od.ProductID == 42).Select( od => od.OrderID );
var intersection = o1.Intersect(o2);

(, ) :

(from o1 in OrderDetails
join o2 in OrderDetails on o1.OrderID equals o2.OrderID
where o1.ProductID == 11 and o2.ProductID == 42
select o1.OrderID).Distinct()
+1

Source: https://habr.com/ru/post/1736337/


All Articles