C# LINQ JOIN + GROUP BY + SUM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2308374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:17:10  来源:igfitidea点击:

LINQ JOIN + GROUP BY + SUM

c#linqgroup-bysumaggregate

提问by JohnBob

I have two LINQ statements that I would like to make into one, but for the life of me I can't get it to work.

我想将两个 LINQ 语句合二为一,但在我的一生中,我无法让它发挥作用。

I can't get the grouping to work in the first statement. It complains that the TotalBuyand TotalSellproperties aren't there, although doesn't complain about AmountTCand AmountAUD.

我无法在第一个语句中进行分组。它抱怨TotalBuyTotalSell属性不存在,尽管没有抱怨AmountTCAmountAUD

This should be simple. Any thoughts?

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

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

As a side note, ItineraryItemRecordsand TransactionRecordsare Collections of classes handled by SubSonic.

作为旁注,ItineraryItemRecordsTransactionRecords是由SubSonic.

This really should be simple, so any help would be appreciated.

这真的应该很简单,所以任何帮助将不胜感激。

Regards, John

问候, 约翰

采纳答案by Amy B

A minor mistake, corrected:

一个小错误,更正:

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

I recommend against re-using identifiers - will help avoid these mistakes in the future.

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