c# - LINQ JOIN + GROUP BY + SUM

标签 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 处理的类的集合。

这真的应该很简单,因此我们将不胜感激。

问候, 约翰

最佳答案

一个小错误,更正:

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))) 
   }; 

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

关于c# - LINQ JOIN + GROUP BY + SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308374/

相关文章:

c# - 格式化 ESRI 地理编码器的 RestSharp 请求

c# - 在低质量图像中查找简单对象

c# - 如何使用 Linq 从父列表中选择和分组复杂的子对象

mysql - 对多列进行分组时如何选择最大值或最后一条记录?

python - 对列表内的值进行分组

mysql - 无法在 mysql 中使用 group by 获得正确的结果

c# - 为什么角色即使存在于数据库中也显示为 "not exist"(asp.net mvc)

c# - 将纬度和经度转换为 double 值的最简单方法是什么

c# - 如何递归迭代日期的数字和总和?

c# - Linq 中的WhereSelectArrayIterator 是什么?