LINQ JOIN + GROUP BY + SUM

时间:2010-02-22 01:54:50

标签: c# linq group-by sum aggregate

我有两个LINQ语句,我想把它变成一个,但对于我的生活,我无法让它工作。

我不能让分组在第一个语句中工作。 它抱怨TotalBuyTotalSell属性不存在,但不会抱怨AmountTCAmountAUD

这应该很简单。有什么想法吗?

var itineraryItems =
    from ii in this.ItineraryItemRecords
    join t in this.TransactionRecords on ii.OperatorID equals t.
    TransactionActor.OperatorID into g select new {
    OperatorID = ii.OperatorID, TotalBuy = g.Sum(i = >ii.TotalBuy)
        , TotalSell = g.Sum(i = >ii.TotalSell)
        , PaidTC = (0 - (g.Sum(t = >t.AmountTC)))
        , PaidAUD = (0 - (g.Sum(t = >t.AmountAUD)))
};

var itineraryItemz =
    from i in itineraryItems group i by i.OperatorID into g select new {
    OperatorID = g.Key, TotalBuy = g.Sum(i = >i.TotalBuy)
        , TotalSell = g.Sum(i = >i.TotalSell)
        , PaidTC = (0 - (g.Sum(i = >i.PaidTC)))
        , PaidAUD = (0 - (g.Sum(i = >i.PaidAUD)))
};

作为旁注,ItineraryItemRecordsTransactionRecords是由SubSonic处理的类集合。

这真的应该很简单,所以任何帮助都会受到赞赏。

此致 约翰

1 个答案:

答案 0 :(得分:10)

一个小错误,纠正了:

var itineraryItems = from ii in this.ItineraryItemRecords 
   join t in this.TransactionRecords on ii.OperatorID equals t.TransactionActor.OperatorID 
   into g 
   select new 
   { 
       OperatorID = ii.OperatorID 
       //, TotalBuy = g.Sum(i => ii.TotalBuy) 
       , TotalBuy = g.Sum(i => i.TotalBuy) 
       //, TotalSell = g.Sum(i => ii.TotalSell) 
       , TotalSell = g.Sum(i => i.TotalSell) 
       , PaidTC = (0 - (g.Sum(t => t.AmountTC))) 
       , PaidAUD = (0 - (g.Sum(t => t.AmountAUD))) 
   }; 

我建议不要重复使用标识符 - 这将有助于避免将来出现这些错误。