Home > OS >  C# Group a date range in parts according to a specific number of days
C# Group a date range in parts according to a specific number of days

Time:10-21

I have a list on Dates:

2021/09/01
2021/09/02
2021/09/03
2021/09/04
2021/09/05
2021/09/06
2021/09/07
2021/09/08
2021/09/09
......

2021/09/29

How to group date range in 7-day chunks?:

2021/09/01
2021/09/02
2021/09/03
2021/09/04
2021/09/05
2021/09/06
2021/09/07

2021/09/08
2021/09/09
2021/09/10
2021/09/11
2021/09/12
2021/09/13
2021/09/14

....

CodePudding user response:

You can use LINQ's GroupBy, divide the index through 7:

List<List<DateTime>> weekGroups = dates
    .Select((date, index) => (date, index))
    .GroupBy(x => x.index / 7, x => x.date)
    .Select(g => g.ToList())
    .ToList();

CodePudding user response:

If you have data that might contain gaps or several entries for a date, you can calculate the difference to the minimum date and use it for grouping, e.g.:

if (dates.Any()) // Min() will fail if there are no dates
{
  var minDate = dates.Min(x => x);
  var interval = 7d;
  var groups = from x in dates 
               group x by x.Subtract(minDate).TotalDays / interval 
               into g 
               select g;
}

The above sample can be used as a guideline; you might need to adjust it to your data structures and requirements.

  • Related