从Linq的另一个表中分组一个表和总和

时间:2014-11-27 15:03:28

标签: c# linq

我有这个Linq查询:

from i in data.Items
join tdi in data.TDItems on i.itemId equals tdi.itemId
group i by i.ItemId
into selection 
select new
{
    itemId = selection.Key
    number = selection.Sum(x => x.quantity) // quantity is a field in TDItems
}

如何创建此求和函数?因为我按照Items表中的属性进行分组,所以我不能在TDItems表上调用Sum。

2 个答案:

答案 0 :(得分:2)

group new { i, tdi } by i.ItemId
...
select new 
{
   selection.Sum(x => x.tdi.quantity)
}

答案 1 :(得分:0)

          from c in (from i in @as 
                join tdi in bs on i.itemId equals tdi.itemId
        select new
        {
            itemId = i.itemId,
            quantity = tdi.quantity
        })
        group c by c.itemId
        into selection
        select new
        {
            itemId = selection.Key,
            number = selection.Sum(x => x.quantity) // quantity is a field in TDItems
        };