Reputation: 1763
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);
}
Upvotes: 26
Views: 25889
Reputation: 6793
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 that date
is set to the result of AddDays
.
for (var date = StartDate; date <= EndDate; date = date.AddDays(1))
{
selectedDates.Add(date);
}
Upvotes: 42
Reputation: 114461
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:
DateTime StartDate = new DateTime(1979, 10, 4);
DateTime EndDate = new DateTime(2016, 10, 4);
var dates = Enumerable.Range(0, (EndDate - StartDate).Days + 1)
.Select(day => StartDate.AddDays(day))
If you need it to be Nullable, add:
.Cast<DateTime?>()
If you need this to be a List, add:
.ToList()
It's probably quite a bit more efficient than the other LINQ based solution.
Upvotes: 7
Reputation: 186668
LINQ solution (let's generate selectedDates
):
var selectedDates = Enumerable
.Range(0, int.MaxValue)
.Select(index => new DateTime?(StartDate.AddDays(index)))
.TakeWhile(date => date <= EndDate)
.ToList();
Upvotes: 32
Reputation: 98740
As far as I can see, since AddDays
method returns a new instance of a DateTime
, it does not change the current instance since DateTime
is immutable.
Looks like your date
is DateTime?
, you can change this part as;
for (var date = StartDate; date <= EndDate; date = date.Value.AddDays(1))
{
selectedDates.Add(date);
}
As usr pointed, this might be affected on DST. You might wanna check Dmitry's answer as well.
Upvotes: 12
Reputation: 10055
Decided to change it up with a do/while
var selectedDates = new List<DateTime?>();
DateTime? StartDate = DateTime.Parse("01/04/2016 00:00:00");
DateTime? EndDate = DateTime.Parse("10/04/2016 00:00:00");
do
{
selectedDates.Add(StartDate);
StartDate = StartDate.Value.AddDays(1);
}while(StartDate < EndDate);
Upvotes: 1