【问题标题】:foreach day in month [duplicate]每月的每一天[重复]
【发布时间】:2012-02-24 04:54:06
【问题描述】:

可能重复:
How do I loop through a date range?

有没有办法为特定月份的每一天创建一个 foreach 循环?

想到类似的事情

foreach (DateTime date in DateTime.DaysInMonth(2012, 1))
{
}

【问题讨论】:

  • 你每天需要做什么?您需要完整的日期还是每天的数值?
  • 我实际上认为如果 DateTime 确实为请求的日期范围返回 IEnumerable 会很棒。
  • @sll 我正在制作一个可以看到全年的日历,并且人们可以在单个日期上做笔记

标签: c# asp.net .net foreach


【解决方案1】:

你可以很容易地编写一个辅助方法:

public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
    int days = DateTime.DaysInMonth(year, month);
    for (int day = 1; day <= days; day++)
    {
         yield return new DateTime(year, month, day);
    }
}

然后调用它:

foreach (DateTime date in AllDatesInMonth(2012, 1))

这对于你只做一次一次的事情来说可能是多余的,但如果你经常这样做,它比使用for 循环或类似的东西要好得多。它让你的代码只是说出你想要实现的目标,而不是你如何做的机制。

【讨论】:

  • 最好将这个函数的前两行替换为:foreach(var day in Enumerable.Range(1, DateTime.DaysInMonth(year, month))
  • 我觉得这个问题刚刚被问到了。
  • 如果您使用 linq,您可以更进一步,方法是将函数内的所有行替换为:return Enumerable.Range(1, DateTime.DaysInMonth(year, month)).Select( day => new DateTime(year, month, day));
  • @Aston:是的,绝对的。
【解决方案2】:

尝试使用 for 循环。

for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++)
{
  DateTime dt = new DateTime(year, month, i);
}

【讨论】:

    【解决方案3】:

    你可以使用范围:

    Enumerable
        .Range(1, DateTime.DayInMonth(2012, 1)
        .Select(i => new DateTime(2012, 1, i)))
        .ToList() // ForEach is not a Linq to Sql method (thanks @Markus Jarderot)
        .ForEach(day => Console.Write(day));
    

    【讨论】:

    • 或者更进一步Enumerable.Range(1, DateTime.DayInMonth(2012, 1)).Select(day =&gt; new DateTime(2012, 1, day))
    • @Ray,谢谢!好主意
    • 我无法正常工作Enumerable .Range(1, DateTime.DaysInMonth(2012, 1)) .Select(i =&gt; new DateTime(2012, 1, i)) .ForEach(day =&gt; Console.Write(day));错误 CS1061:类型 System.Collections.Generic.IEnumerable 不包含 ForEach 的定义,并且找不到 System.Collections.Generic.IEnumerable 类型的扩展方法 ForEach。您是否缺少程序集参考? (CS1061)
    • @testing,可能需要using System.Linq
    • IEnumerable&lt;T&gt;.ForEach 不是 LINQ 的扩展方法。该方法在(现在旧的)LINQ Extensions Library 中提供。 BCL 中最简单的替代方法是使用 .ToList().ForEach(...)
    【解决方案4】:

    你可以用一个简单的循环来做到这一点:

    DateTime first = new DateTime(2012, 1, 1);
    for (DateTime current = first ; current.Month == first.Month ; current = current.AddDays(1)) {
    }
    

    【讨论】:

    • 我喜欢利用经常被忽视的功能来使用非 int 数据类型的 for 循环。
    【解决方案5】:

    生成天数的枚举相当容易。这是一种方法

    Enumerable.Range(1, DateTime.DaysInMonth(year, month)).Select(day =>
        new DateTime(year, month, day))
    

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      相关资源
      最近更新 更多