I would like to get dates between two dates. Instead of expected 9 different dates, I get 875287 and run out of memory. What would be the problem with the code below?
StartDate
value is 01/04/2016 00:00:00
EndDate
value is 10/04/2016 00:00:00
var selectedDates = new List<DateTime?>();
for (var date = StartDate; date <= EndDate; date.Value.AddDays(1))
{
selectedDates.Add(date);
}
LINQ solution (let's generate
selectedDates
):Decided to change it up with a do/while
A shorter notation using Linq's Range method uses the ability to already figure out the number of days using the
TimeSpan.Days
property after subtracting start from end.Assuming the start is before end you'd end up with:
If you need it to be Nullable, add:
If you need this to be a List, add:
It's probably quite a bit more efficient than the other LINQ based solution.
You aren't assigning the value of
date.Value.AddDays(1)
to anything, so it ends up in an infinite loop. You'd need to change your code so thatdate
is set to the result ofAddDays
.As far as I can see, since
AddDays
method returns a new instance of aDateTime
, it does not change the current instance sinceDateTime
is immutable.Looks like your
date
isDateTime?
, you can change this part as;As usr pointed, this might be affected on DST. You might wanna check Dmitry's answer as well.