Programming Basics: The for loop can do more than increment an integer


This is one of those small things that is easy to forget.  Usually when we use a for loop, we’ll just incrment over an integer so that we can get a specific item out of some iteration.  But you can do much more than that.  My current project has a complicated scheduling component and I’m often working with a range of dates.  I often need to do something with the days between two dates.  I created a TimePeriod class that is created with a start and end date.

public class TimePeriod
    {
        private readonly DateTime _start;
        private readonly DateTime _end;

        public TimePeriod(DateTime start, DateTime end)
        {
            _start = start;
            _end = end;
        }

       …

}

Now what I need to do is iterate over all of the days that are between these two dates.  I was struggling with this for a while, trying get a clean implementation.  Then I remembered that the for loop could do this for me.  Instead of using the standard i++ of the loop action, I add a day to the iteration variable.  Now I can get every day between the start and end date.

public IEnumerable DaysInPeriod() {       for(var d = \_start; d <= \_end; d = d.AddDays(1))       {            yield return d;       } }

Once I had this in place, I was able to put on some more convenience methods to cut down on some repetitive tasks I was performing.

public bool Contains(DateTime dateTime)
{
      return DaysInPeriod().Contains(dateTime);
}

public bool ContainsTheDayOfWeek(DayOfWeek dayOfWeek)
{
     return DaysInPeriod().Any(d => d.DayOfWeek == dayOfWeek);       
}

This was nothing Earth shattering, but a real simple abstraction made my life a lot easier.

 

 

Ruby and Rake as an executable