我甚至不知道如何做到这一点,而不使用一些可怕的循环/计数器类型的解决方案。问题是这样的:
我有两个日期,一个开始日期和一个结束日期,在指定的时间间隔内,我需要采取一些行动。例如:对于3/10/2009之间的每个日期,每隔三天直到3/26/2009,我需要在列表中创建一个条目。所以我的输入是:
DateTime StartDate = "3/10/2009";
DateTime EndDate = "3/26/2009";
int DayInterval = 3;
我的输出将是一个具有以下日期的列表:
3/13/2009
3/16/2009
3/19/2009
3/22/2009
3/25/2009
那我要怎么做这种事呢?我考虑过使用一个for循环,它会在每天的范围内迭代,并使用一个单独的计数器,如下所示:
int count = 0;
for(int i = 0; i < n; i++)
{
count++;
if(count >= DayInterval)
{
//take action
count = 0;
}
}
但似乎还有更好的办法?
来自@mquander和@Yogurt The Wise的代码用于扩展:
public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1))
yield return month;
}
public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
return EachDay(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
return EachMonth(dateFrom, dateTo);
}
来自@mquander和@Yogurt The Wise的代码用于扩展:
public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1))
yield return month;
}
public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
return EachDay(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
return EachMonth(dateFrom, dateTo);
}