Un método alternativo que podría ser más reutilizable es escribir un método de extensión en la fecha y hora y devolver un IEnumerable.
Por ejemplo, puede definir una clase:
public static class MyExtensions
{
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
// Remove time info from start date (we only care about day).
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
}
Ahora en el código de llamada se puede hacer lo siguiente:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Otra ventaja de este enfoque es que hace que sea trivial agregue EachWeek, EachMonth etc. A continuación, todos estarán accesibles en DateTime.
Echa un vistazo aquí: http://stackoverflow.com/questions/533767/how-do-you-iterate-through-every-day-of-the-year –