C# – Iterate between two dates in C#

cdatetime

I have two dates:

DateTime fromDate = new DateTime(2013,7,27,12,0,0);
DateTime toDate = new DateTime(2013,7,30,12,0,0);

I want to iterate from fromDate to toDate by incrementing fromDate with a single day and the loop should break when fromDate becomes equal to or greater than the toDate. I have tried this:

while(fromDate < toDate)
{
fromDate.AddDays(1);
}

But this is an infinite loop and won't stop. How can I do this ?

Best Answer

Untested but should work:

for(DateTime date = fromDate; date < toDate; date = date.AddDays(1)) {
}

Modify the comparison to <= if you want to include toDate as well.