Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何按日期时间对字典进行分组并对int进行求和_C#_Linq_Lambda_Group By_Aggregate Functions - Fatal编程技术网

C# 如何按日期时间对字典进行分组并对int进行求和

C# 如何按日期时间对字典进行分组并对int进行求和,c#,linq,lambda,group-by,aggregate-functions,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.V

我有以下代码:

    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
...

您可以使用匿名类型同时获取:
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)
                                  }));

请参阅按月份分组。确实非常有用。:)
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)
                                  }));