c# – 如何按dateTime对字典进行分组,并对int进行求和

我有这个代码:

    var tradeReqsBySegment = segGroups.Join(pPeriods, s => s.MarketSegmentId, p => p.EntityId, (s, p) => new
    {
        SegmentCode = s.SegmentCode, // string
        Time = p.StartLocal, // datetime
        TradeRequirement = p.Volume // double
    })
    .GroupBy(s => s.SegmentCode)
    .ToDictionary(g => g.Key, g => g.ToDictionary(i => i.Time, i=>i.TradeRequirement));

我希望按时间对g.ToDictionary(i => i.Time,i => i.TradeRequirement)进行分组,并将TradeRequirement汇总或平均.我该如何处理?

此外,是否可以按月分组时间,如获取:

Time - TradeReq
01/2013 - 500
02/2013 - 234
...

最佳答案

g.GroupBy(gr => new DateTime(gr.Time.Year, gr.Time.Month, 1))
         .ToDictionary(i => i.Key, i => i.Sum(s => s.TradeRequirement));
点赞