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

发布于 2024-12-01 07:23:59 字数 552 浏览 1 评论 0原文

我有一个日期集合:

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

请注意,上述是我的想法,但我非常愿意接受有关实现此目的的其他方法的建议。

I have a collection of dates:

 IEnumerable<DateTime> Events;

And I want to count and bucket then into quarters (Q1 2011, Q2 2011, etc.) where each quarter represents three-month buckets.

I started doing this "manually" with a loop and a separate dictionary, but I thought there might be a more elegant way using LINQ, etc. to do this conversion.

I want to end up with a data structure that looks like this:

 public List<QuarterInfo> QuarterBreakdown

where QuarterInfo is simply:

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

NOTE that the above was my thinking, but I am more than open to suggestions on other ways of achieving this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三生路 2024-12-08 07:23:59

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

Pure LINQ, using 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
        });
热风软妹 2024-12-08 07:23:59
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
    };
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
    };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文