c# - 在 C# 中循环当前年月到下年月

标签 c# asp.net loops

我遇到了一个问题,我程序中写的逻辑如下

while (lastDate.Month < DateTime.Today.Month - 1)//
  {
    lastDate= lastDate.AddMonths(1);
    list.Add(lastDate);
  }

当 lastDate 月份是 Dec 并且我在新年的 1 月或 2 月执行此代码时,此代码失败,因为 12 永远不会大于 1 0r 2。

我需要编写一个逻辑,使我的循环可以遍历 Nov、Dec、Jan、Feb 等等。

我写了下面的代码,但我没有得到退出的线索,当 lastDate 和今天的日期相差 2 个月时,循环应该退出。

if (lastDate.Month > DateTime.Today.Month && lastDate.Year < DateTime.Today.Year)
 {
  while (lastDate.Year <= DateTime.Today.Year)
   {
     lastDate= lastDate.AddMonths(1);
     list.Add(lastDate);

   }

请帮帮我

最佳答案

您总是会在列表中添加 12 个月,因此您可以使用 for 循环:

for(var i = 0; i < 12; i++)
{
    lastDate = lastDate.AddMonths(1);
    list.Add(lastDate);
}

正如您知道必须将一个月加多少次一样,不需要根据月份和年份来设置条件,而只需要一个计数器来恰好执行此代码 12 次。

关于c# - 在 C# 中循环当前年月到下年月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16272498/

相关文章:

c# - 从 Compact .Net 1.0 应用程序启动另一个应用程序

asp.net - session 固定 - 表单例份验证

.net - 对 asp .net 应用程序进行单元测试时如何使用 web.config

asp.net - ExecuteScalar、ExecuteReader 和 ExecuteNonQuery 之间有什么区别?

目录上的 Bash For 循环

c# - Xamarin 中的 WebException,使用 HttpClient

c# - 在 C# 中使用默认引用对象关系访问属性的默认值

c# - 在 EntityFramework 6.0 和 .NET 4.5 中使用 oracle sdo_geometry

javascript - 从 Google 表格循环

c++ - 在 c++ 中的 unordered_map 中仅访问一对元素中的一个元素