6.3.1 Iterating over the dates in a timetable
While working on a project involving timetables, I came across a few loops, all of
which started like this:
for (DateTime day = timetable.StartDate;
day <= timetable.EndDate;
day = day.AddDays(1))
I was working on this area of code quite a lot, and I always hated that loop, but it was
only when I was reading the code out loud to another developer as pseudo-code that I
realized I was missing a trick. I said something like, ???For each day within the timetable.???
In retrospect, it??™s obvious that what I really wanted was a foreach loop. (This
may well have been obvious to you from the start??”apologies if this is the case. Fortunately
I can??™t see you looking smug.) The loop is much nicer when rewritten as
foreach (DateTime day in timetable.DateRange)
In C# 1, I might have looked at that as a fond dream but not bothered implementing
it: we??™ve seen how messy it is to implement an iterator by hand, and the end result
6 The Microsoft C# 3 compiler shipping with .NET 3.5 behaves in the same way.
174 CHAPTER 6 Implementing iterators the easy way
only made a few for loops neater in this case. In C# 2, however, it was easy. Within the
class representing the timetable, I simply added a property:
public IEnumerable
DateRange
{
get
{
for (DateTime day = StartDate;
day <= EndDate;
day = day.
Pages:
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348