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<DateTime> 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.

 

 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • aly

    wtf?

  • I second that WTF. I don’t even recognize the language. I thought I was reading Java up until the “for(var d …” part. What language is that?