Oh, it's very easy to iterate over dates - this is not a problem at all:
You can also easily write IEnumerable<DateTime> and use foreach .
I would try to avoid doing string operations here if possible, although, in fact, these dates are not strings, so if you can work in the problem area as much as possible, this will simplify the work.
Of course, there may be more effective ways than a cycle, but it will be more difficult for them to succeed. If the loop is ok in terms of performance, I will stick with this.
As a quick plugin for my own open source project, Noda Time has a more diverse set of types representing dates and times - in which case you will use LocalDate . Thus, you do not need to worry about what happens if the time at the “start” is later than the time at the “end”, etc. On the other hand, Noda Time is not over yet ... the bits you need for this are ready and should work fine, but it is possible that the API may still change in the future.
EDIT: If you often need to quote dates, you might need something like this extension method (put it in a nonequivalent static top-level class):
public static IEnumerable<DateTime> To(this DateTime start, DateTime end) { Date endDate = end.Date; for (DateTime date = start.Date; date <= endDate; date = date.AddDays(1)) { yield return date; } }
Then:
foreach (DateTime date in start.To(end)) { ... }
Jon skeet
source share