Linq中的多重分组,内部循环

时间:2009-07-08 14:12:19

标签: linq

我正在尝试将其翻译成Linq并且无法弄清楚:

SELECT
    CustomerOrder.ShipState, MONTH(OrderFulfillment.OrderDate) AS Mnth,
    YEAR(OrderFulfillment.OrderDate) AS Yer,
    SUM(OrderFulfillment.Tax) AS TotalTax
FROM
    OrderFulfillment INNER JOIN
        CustomerOrder ONOrderFulfillment.OrderID =CustomerOrder.OrderID
WHERE
    (OrderFulfillment.Tax > 0)
GROUP BY
    CustomerOrder.ShipState, MONTH(OrderFulfillment.OrderDate),
    YEAR(OrderFulfillment.OrderDate)
ORDER BY
    YEAR(OrderFulfillment.OrderDate) DESC, CustomerOrder.ShipState,
    MONTH(OrderFulfillment.OrderDate) DESC

我有Linqpad并且经历过一系列示例,但无法弄清楚这一点。

2 个答案:

答案 0 :(得分:0)

首先,很高兴知道你究竟弄清楚了什么。如果你完全迷失了,不知道从哪里开始那么你需要谷歌周围的linq加入和分组。

这是我最近做的事情,可能(可能)指出你正确的方向:

// This groups items by category and lists all category ids and names
from ct in Categories
  join cst in Category_Subtypes 
    on ct.Category_Id equals cst.Category_Id
  join st in Subtypes
    on cst.Subtype_Id equals st.Subtype_Id
where 
  st.Type_Id == new Guid(id)
group ct by new { ct.Category_Id, ct.Display_Text } into ctg
select new 
{
    Id = ctg.Key.Category_Id,
    Name = ctg.Key.Display_Text
}

答案 1 :(得分:0)

我想你想做这样的事情:

from c in CustomerOrder
    join o in OrderFulfillment on c.OrderId equals o.OrderId
where 
    o.Tax > 0
group o by 
    new { c.ShipState, Mnth = of.OrderDate.Month, Yer = of.OrderDate.Year } 
        into g
orderby
    g.Key.Yer descending, g.ShipState, g.Key.Mnth descending
select
    new { g.Key.ShipState, g.Key.Mnth, g.Key.Yer, 
    TotalTax = g.Sum(i => i.Tax) };

我没有尝试编译它,但我认为这是你想要的东西。

这个想法是首先执行您的联接以链接客户和订单。然后应用您的过滤条件。

此时,您希望获得具有特定组的所有订单,因此应用了组运算符。

最后,订购结果,然后从每个组的键中选出所有信息,并总结每个组中的税。