Create an array or List of all dates between two dates [duplicate]
Solution 1:
LINQ:
Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.ToArray();
For loop:
var dates = new List<DateTime>();
for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
dates.Add(dt);
}
EDIT: As for padding values with defaults in a time-series, you could enumerate all the dates in the full date-range, and pick the value for a date directly from the series if it exists, or the default otherwise. For example:
var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date)
? timeSeries[date] : defaultValue);
Solution 2:
public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
if (endDate < startDate)
throw new ArgumentException("endDate must be greater than or equal to startDate");
while (startDate <= endDate)
{
yield return startDate;
startDate = startDate.AddDays(1);
}
}