I have a start and an end date and I want to get a list of all the days between those 2 dates (inclusive). I can do this with a loop that adds 1 day to the start date then adds that date to a list. Something like:
DateTime end = DateTime.Now;
DateTime start = end.AddDays(-30);
DateTime current = start;
List<DateTime> result = new List<DateTime>();
while (currrent <= end)
{
result.Add(current);
current = current.AddDays(1);
}
I'm looking for a tidy LINQ expression instead. Any ideas?
If you know the start and end, it's simple just to write a method using an iterator block to do this:
public static IEnumerable<DateTime> DateRange(DateTime startInclusive, DateTime endInclusive)
{
for (var current = startInclusive; current <= endInclusive; current = current.AddDays(1))
{
yield return current;
}
}
If you know the number of days instead, then Cory's answer works well.
My method above could also be overloaded to take a TimeSpan
for the "step" between iterations.
See more on this question at Stackoverflow