Linq to Object Time Cycle

I want to do this with LINQ to Object

    List<DateTime> allDays = new List<DateTime>(); 
    DateTime start = new DateTime(2010, 1, 1);
    DateTime maxDate = new DateTime(2010, 1, 11);
    do
    {
        allDays.Add(start);
        start = start.AddDays(1);
    }
    while (maxDate.Date >= start);

Thank.

+3
source share
1 answer

You can make an extension method as follows:

    public static IEnumerable<DateTime> DaysUpTo(this DateTime startDate, DateTime endDate)
    {
        DateTime currentDate = startDate;
        while (currentDate <= endDate)
        {
            yield return currentDate;
            currentDate = currentDate.AddDays(1);
        }
    }

Then you can use it as follows:

        DateTime Today = DateTime.Now;
        DateTime NextWeek = DateTime.Now.AddDays(7);

        var weekDays = Today.DaysUpTo(NextWeek).ToList();

Or with the example you used:

DateTime start = new DateTime(2010, 1, 1);
DateTime maxDate = new DateTime(2010, 1, 11);
List<DateTime> allDays = start.DaysUpTo(maxDate).ToList();

Edit:

If you really want to implement LINQ, this will work too:

DateTime start = new DateTime(2010, 1, 1);
DateTime maxDate = new DateTime(2010, 1, 11);

List<DateTime> allDays  = Enumerable
                          .Range(0, 1 +(maxDate - start).Days)
                          .Select( d=> start.AddDays(d))
                          .ToList();
+4
source

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


All Articles