我有这段代码:
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
...
答案 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)
您可以使用匿名类型同时获取Sum
和Average
:
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)
}));