How to get all weekends within date range in C#

DmitryBoyko picture DmitryBoyko · Jul 25, 2014 · Viewed 10.7k times · Source

I am just wondering if there is a simple way or framework to to get all weekends within date range in C#?

Is it possible to do with LINQ as well?

Any clue?

Thank you!

Answer

Mitch picture Mitch · Jul 25, 2014

If you make a way to enumerate all days, you can use linq to filter to weekends:

IEnumerable<DateTime> GetDaysBetween(DateTime start, DateTime end)
{
    for (DateTime i = start; i < end; i = i.AddDays(1))
    {
        yield return i;
    }
}

var weekends = GetDaysBetween(DateTime.Today, DateTime.Today.AddDays(365))
    .Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);