Linq:按年和月分组,并管理空月 [英] Linq: group by year and month, and manage empty months

查看:22
本文介绍了Linq:按年和月分组,并管理空月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Linq 可以按年份和月份对列表进行分组.

I have the following Linq to group a list by year, then by month.

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

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

As you can see, months without value, are not included in the query. I would like to include them, having the following output:

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

换句话说,我还需要获得空月.

In other words, I need to get also empty months.

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

Could I implement this with a Linq query? Thanks in advance

推荐答案

我想你想要这样的:

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

注意:

  • 您需要知道您尝试提供数据的年份.当然,您可以从另一个查询中获取它,以找到所涉及的最小和最大年份 - 或者可能找到最小值并假设将来不会有任何内容(我不知道这是否是一个有效的假设)
  • 这将自动正确排序

这篇关于Linq:按年和月分组,并管理空月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆