代码之家  ›  专栏  ›  技术社区  ›  Daniel Peñalba

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

  •  8
  • Daniel Peñalba  · 技术社区  · 15 年前

    我有下面的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查询实现这个功能吗?提前谢谢

    1 回复  |  直到 15 年前
        1
  •  18
  •   Jon Skeet    15 年前

    我想你想要这样的东西:

    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() };
    

    注意:

    • 你需要知道你打算在几年内拿出数据。当然,你可以从另一个查询中获取这一点,以找到相关的最小和最大年,或者找到最小值,假设将来不会有什么(我不知道这是否是一个有效的假设)。
    • 这将自动正确订购