C # list of past DateTimes

I have a method that returns the past x days, and it currently does the following:

var dates = new List<DateTime>();

for (int i = 0; i < numDays; i++)
{
    dates.Add(DateTime.Today.AddDays(-i));
}

return dates;

I feel that there should be a more compact way to do this, perhaps using LINQ. Suggestions? In addition, if I save it as it is, DateTime.Todayso that it is more efficient if I store it in a variable outside the loop and then call AddDaysthis value in the loop?

Edit: LINQ uses a lazy evaluation, right? I get crazy images in my head:

return DateTime.AllDaysInTheHistoryOfTimeEver.Where(day =>
    day.BeforeOrOn(DateTime.Today) &&
    day.After(DateTime.Today.AddDays(-numDays))
);
+3
source share
4 answers
var start = DateTime.Today;
var days = Enumerable.Range(0, numDays).Select(i => start.AddDays(-i)).ToList();

The capture startfirst avoids turning in the corner during midnight.

+12

, linq, , (.. numDays), 10 .

var dates = GetDates(DateTime.Now.AddDays(-10),DateTime.Now);

 public IEnumerable<DateTime> GetDates(DateTime StartingDate, DateTime EndingDate)
        {
            while (StartingDate <= EndingDate)
            {
                yield return StartingDate;
                StartingDate = StartingDate.AddDays(1);
            }
        } 
+1

Marc , , - , , (... , , - ..)

DateTime.Today, UtcNow.ToLocalTime(), , DateTimeKind.Local:

public virtual DateTime ToLocalTime(DateTime time)
{
    if (time.Kind == DateTimeKind.Local)
    {
        return time;
    }
    bool isAmbiguousLocalDst = false;
    long utcOffsetFromUniversalTime = ((CurrentSystemTimeZone) CurrentTimeZone).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst);
    return new DateTime(time.Ticks + utcOffsetFromUniversalTime, DateTimeKind.Local, isAmbiguousLocalDst);
}
+1

, , IEnumerator IEnumerable yield.

. MSDN

0

Source: https://habr.com/ru/post/1729948/


All Articles