Linq:按年和月分组,并管理空月

我有以下Linq按年分组,然后按月分组。

var changesPerYearAndMonth = list .GroupBy(revision => new { revision.LocalTimeStamp.Year, revision.LocalTimeStamp.Month }) .Select(group => new { GroupCriteria = group.Key, Count = group.Count() }) .OrderBy(x => x.GroupCriteria.Year) .ThenBy(x => x.GroupCriteria.Month); 

我目前的输出如下:

 Year 2005, month 1, count 469 Year 2005, month 5, count 487 Year 2005, month 9, count 452 Year 2006, month 1, count 412 Year 2006, month 5, count 470 ... 

如您所见,查询中不包含没有值的月份。 我想包含它们,具有以下输出:

 Year 2005, month 1, count 469 Year 2005, month 2, count 0 Year 2005, month 3, count 0 ... Year 2005, month 12, count 0 Year 2006, month 1, count 412 Year 2006, month 2, count 0 ... Year 2006, month 12, count 0 

换句话说,我也需要空虚的月份。

我可以用Linq查询实现这个吗? 提前致谢

我想你想要这样的东西:

 var changesPerYearAndMonth = from year in Enumerable.Range(2005, 6) from month in Enumerable.Range(1, 12) let key = new { Year = year, Month = month } join revision in list on key equals new { revision.LocalTimeStamp.Year, revision.LocalTimeStamp.Month } into g select new { GroupCriteria = key, Count = g.Count() }; 

注意:

  • 你需要知道你想要提供数据的年份。 当然,您可以从另一个查询中获取此信息,以查找所涉及的最小和最大年份 – 或者可以找到最小值并假设将来不会有任何内容(我不知道这是否是一个有效的假设)
  • 这将自动正确订购