如何为此编写linq查询?

时间:2012-05-09 18:53:21

标签: c# linq-to-sql

我需要在Linq to SQL中编写以下查询,但不确定最佳方法是什么,因为它有两个派生表。任何建议。

SELECT A.ID  
FROM  
(   
    SELECT *   
    FROM Orders   
    WHERE ProductID = 5  
) A  
JOIN  
(  
    SELECT CustomerID, MAX(Price) Price   
    FROM Orders   
    WHERE ProductID = 5  
    GROUP BY CustomerID  
) B  
ON A.CustomerID = B.CustomerID and A.Price = B.Price  

3 个答案:

答案 0 :(得分:1)

var b = (
    from o in db.Orders
    where o.ProductID == 5
    group o by o.CustomerID into og 
    select new {
        CustomerID = og.Key
        Price = Max(og.Price)
    }
);
var a = (
    from o in db.Orders
    join p in b on new {a.CustomerID, a.Price} equals 
            new {b.CustomerID, b.Price}
    where o.ProductID == 5
    select a.ID
);
var r = a.ToString();

在形成以下内容时,这两个链接非常有用:

答案 1 :(得分:1)

您可以使用LINQ简化此操作,特别是如果您使用方法语法而不是查询语法。

orders.Where(o => o.ProductID == 5)
    .GroupBy(o => o.CustomerID)
    .SelectMany(g => g.Where(o => o.Price == g.Max(m => m.Price)));

我在编写LINQ时的建议,不要简单地尝试完全转换SQL语句。考虑所需的结果并开发专为LINQ设计的解决方案。

答案 2 :(得分:0)

这些方面的东西:

var result = from a in context.Orders
             join b in (context.Orders.Where(o => o.ProductID == 5).GroupBy(o => o.CustomerID).Select(g => new { CustomerID = g.Key, Price = g.Max(o => o.Price)))
                 on new {a.CustomerID, a.Price} equals new {b.CustomerID, b.Price}
             where a.ProductID == 5
             select a.ID;