创建两个日期之间所有日期的数组或列表 [英] Create an array or List of all dates between two dates
问题描述
我正在生成带有 X 轴日期的多系列图表.
I am generating multi-series graphs with the date along the X-Axis.
问题在于,并非图表中的所有系列在日期范围内都具有相同的日期.这意味着,如果我选择 2 月 1 日至 4 月 30 日,则一个系列的数据可能从 2 月 1 日开始,但仅持续到 3 月底,但另一个系列可能具有整个日期范围的数据.
The problem is that not all of the series in the graph have the same dates in the date range. Meaning that if I choose 1 Feb through 30 Apr that one series may have data that starts at 1 Feb but only goes through the end of March but another series may have data for the entire date range.
这会扭曲我需要创建的图表.去吧,鉴于在查询开始时采用的日期范围,我想生成一个日期列表并填充要绘制的数据,用 0 填充那些没有数据的日期的系列.
This skews the charts I need to create. Go, given the date range taken at the begining of the query I'd like to generate a list of dates and populate the data to be graphed, padding those series with 0's for those dates that have no data.
推荐答案
LINQ:
Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.ToArray();
For 循环:
var dates = new List<DateTime>();
for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
dates.Add(dt);
}
至于在时间序列中使用默认值填充值,您可以枚举完整日期范围内的所有日期,并直接从系列中选择日期值(如果存在),否则为默认值.例如:
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);
这篇关于创建两个日期之间所有日期的数组或列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!