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

时间:2013-04-05 15:37:02

标签: c# linq lambda group-by aggregate-functions

我有这段代码:

    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要求总结或平均。我该如何处理?

此外,是否可以按月分组时间,例如get:

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以使用匿名类型同时获取SumAverage

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.GroupBy(gr => new DateTime(gr.Time.Year, gr.Time.Month, 1))
                    .ToDictionary(gr => gr.Key.ToString("MM/yyyy"),
                                  gr => new {
                                      Sum = gr.Sum(s => s.TradeRequirement),
                                      Avg = gr.Average(s => s.TradeRequirement)
                                  }));