Home >Backend Development >C++ >How to Generate a Date Range Array or List in C#?

How to Generate a Date Range Array or List in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-10 21:21:44507browse

How to Generate a Date Range Array or List in C#?

Generate date range array or list in C#

When generating multiple series of data in a chart that uses dates as the X-axis, it is crucial to have a complete list of dates covering the entire range. This ensures that all series have consistent date values, even if they don't have data for all dates.

LINQ methods

An efficient way is to use LINQ:

<code class="language-csharp">Enumerable.Range(0, 1 + end.Subtract(start).Days)
          .Select(offset => start.AddDays(offset))
          .ToArray();</code>

This code creates a list of dates starting at the start of the date range (start) and incrementing once per day until the end of the range (end) is reached.

For loop method

Alternatively, you can use a for loop:

<code class="language-csharp">var dates = new List<DateTime>();

for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
   dates.Add(dt);
}</code>

This loop creates a list of dates in the same way as the LINQ method.

Fill value

To fill in the default value of a series for missing dates, you can enumerate all dates in the full range and fill them in:

<code class="language-csharp">var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date) 
                                               ? timeSeries[date] : defaultValue);</code>

This code creates a dictionary where the keys are dates and the values ​​are data. If a date exists in the series, its corresponding value is retrieved; otherwise, a default value is assigned.

The above is the detailed content of How to Generate a Date Range Array or List in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn