user3818229 user3818229 - 2 months ago 26
C# Question

Group by all full weeks between date period - LINQ

I know how to count number of weeks between two dates.

I have a date period (start date and end date).
Is it possible to get

Tuple<DateTime, DateTime>
or something where
item_1
is a start day of week and
item_2
is the end? I mean I finally want to see
List<Tuple<DateTime, DateTime>>
.

For example my period is from 13/09/16 till 5/10/16
As a result I want to see a list with two corteges:


  1. 19/09/16 - 25/09/16

  2. 26/09/16 - 2/10/16



I have wrote a regular cycle for this but want to have LINQ.

for (var day = start.Date; day.Date <= end.Date; day = day.AddDays(1))
{
if (day.DayOfWeek == DayOfWeek.Monday)
{
if (day.AddDays(6) < end.Date)
result.Add(Tuple.Create(day.Date, day.AddDays(6).Date));
}
}


Also it would be nice to include culture info if a week starting from Sunday like in USA.

Answer

It's very crude... but try something like this:

DateTime start = DateTime.Parse("13/09/16");
DateTime end = DateTime.Parse("5/10/16");

CultureInfo culture = Thread.CurrentThread.CurrentCulture;

Enumerable.Range(0, (end - start).Days)
    .Where(x => start.AddDays(x).DayOfWeek == culture.DateTimeFormat.FirstDayOfWeek)
    .Select(x => new Tuple<DateTime, DateTime>(start.AddDays(x), start.AddDays(x + 6)))
    .Where(x => x.Item2 < end);

This will enumerate to:

| index |  first  |  second |
-----------------------------
|   0   | 19/09/16| 25/09/16|
|   1   | 26/09/16| 2/10/16 |