Ivan Korytin
Ivan Korytin

Reputation: 1842

Date time cycle by Linq to Object

I want to do it using 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 you.

Upvotes: 3

Views: 532

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160902

You could do an extension method like this:

    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 like this:

        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 your really want a LINQ implementation this would 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();

Upvotes: 4

Related Questions