Reputation: 142
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.
Upvotes: 5
Views: 1244
Reputation: 460068
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)
});
Upvotes: 5