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
  • 7,887
  • 5
  • 38
  • 56

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ᴏʀʏ
  • 101,556
  • 20
  • 162
  • 188
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,335,956
  • 823
  • 8,931
  • 9,049