创建两个日期之间的所有日期的数组或列表

我正在生成日期沿X轴的多系列图。

问题在于,并非图表中的所有系列在日期范围内都具有相同的日期。这意味着,如果我选择2月1日到4月30日,则一个系列的数据可能从2月1日开始,但只持续到3月底,而另一个系列的数据可能涵盖整个日期范围。

这扭曲了我需要创建的图表。给定查询开始时的日期范围,我想生成一个日期列表,并填充要绘制图表的数据,对于没有数据的日期,用0填充这些系列。

166469 次浏览

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);
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);
}
}

Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.

I know this is an old post but try using an extension method:

    public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
}

and use it like this

    var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));

Feel free to choose your own dates, you don't have to restrict yourself to January 2000.