按季度计算日期集合的最佳方法是什么?

时间:2011-08-24 11:21:58

标签: c# .net linq collections

我有一系列日期:

 IEnumerable<DateTime> Events;

我想计算并进入季度(2011年第一季度,2011年第二季度等),其中每个季度代表三个月的桶。

我开始使用循环和单独的字典“手动”执行此操作,但我认为使用LINQ等进行此转换可能会有更优雅的方式。

我希望最终得到一个如下所示的数据结构:

 public List<QuarterInfo> QuarterBreakdown

其中QuarterInfo只是:

 public class QuarterInfo
 {
     public int QuarterOfYear; //1, 2, 3 or 4
     public int Year;
     public IEnumerable<DateTime> Events;
 }

请注意,以上是我的想法,但我对其他实现这一目标的方法持开放态度。

2 个答案:

答案 0 :(得分:5)

Pure LINQ,使用GroupBy

var result = Events
    .Select(d => new { DateTime = d, Q = (d.Month - 1) / 3 })
    .GroupBy(a => new { a.Q, a.DateTime.Year })
    .Select(a => new QuarterInfo
        {
            Events = a.Select(s => s.DateTime),
            QuarterOfYear = a.Key.Q + 1
        });

答案 1 :(得分:1)

var QuarterBreakdown =
    from date in Events
    group date by date.Year * 4 + (date.Month - 1) / 3 into quarters
    select new QuarterInfo
    {
        Events = quarters,
        Year = quarters.Key / 4,
        QuarterOfYear = quarters.Key % 4 + 1
    };
相关问题