5

I have a list of DateTime values and I want to split the whole list into sublists for each week.

The dates might span across multiple years(the user selects the start and end date), so a solution that splits them up per calendar week number would end up in conflicts.

Is there a way to traverse the list and then store each week's DateTime values in a new 2d list?

The values available are from Monday to Friday and first and last week might have fewer values.

The only relevant question I found is How to group dates by weeks but it is not suitable for my case.

vkoukou
  • 140
  • 2
  • 15
  • something like this except grouping by the year and week number: https://stackoverflow.com/questions/363655/c-sharp-list-groupby-2-values ? – mikelegg Oct 26 '17 at 11:50
  • If you multiple the year by 100 and then added the week it would give a unique grouping. then you would have to handle the case were the week spanned over two years. So you would test for week 1 and if it started on Sunday then include in current year, otherwise, subtract one from the year and add 53. – jdweng Oct 26 '17 at 11:53
  • would also work although it hides the meaning a bit – mikelegg Oct 26 '17 at 11:55

1 Answers1

5

You can use this method to get the week-number of a given DateTime. Then you can use Enumerable.GroupBy with an anonymous type containing the year and the weeknum:

var yearWeekGroups = allDates.GroupBy(d => new { d.Year, WeekNum = GetIso8601WeekOfYear(d) });

If you want a List<List<DateTime>> where each sub-list contains the dates of a week:

List<List<DateTime>> allWeeks = yearWeekGroups.Select(g => g.ToList()).ToList();

If your country doesn't use ISO 8601 you can use Calendar.GetWeekOfYear:

var cc = CultureInfo.CurrentCulture;
var yearWeekGroups = allDates.GroupBy(d => new 
{ 
    d.Year, 
    WeekNum = currentCulture.Calendar.GetWeekOfYear(d, cc.DateTimeFormat.CalendarWeekRule, cc.DateTimeFormat.FirstDayOfWeek) 
});
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939