Một phương pháp thay thế có thể tái sử dụng nhiều hơn là viết một phương pháp mở rộng trên DateTime và trả về một IEnumerable.
Ví dụ, bạn có thể định nghĩa một lớp:
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);
}
}
}
Bây giờ trong mã gọi bạn có thể làm như sau:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Một ưu điểm khác để tiếp cận này là nó làm cho nó tầm thường để thêm EveryWeek, EachMonth, vv. Sau đó, tất cả sẽ được truy cập trên DateTime.
Hãy xem ở đây: http://stackoverflow.com/questions/533767/how-do-you-iterate-through-every-day-of-the-year –