我有以下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);
Run Code Online (Sandbox Code Playgroud)
我目前的输出如下:
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
...
Run Code Online (Sandbox Code Playgroud)
如您所见,查询中不包含没有值的月份.我希望包含它们,具有以下输出:
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
Run Code Online (Sandbox Code Playgroud)
换句话说,我也需要空虚的几个月.
我可以用Linq查询实现这个吗?提前致谢
Jon*_*eet 18
我想你想要这样的东西:
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() };
Run Code Online (Sandbox Code Playgroud)
注意: