0

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?

HasaniH
  • 8,232
  • 6
  • 41
  • 59

2 Answers2

7

Enumerable.Range would be one option:

var rightNow = DateTime.Now;
var result = Enumerable.Range(1, 30).Select(d => rightNow.AddDays(d)).ToList()
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194