How to group dates by week?

The fundamental question here is how to project a DateTime instance into a week of year value. This can be done using by calling Calendar.GetWeekOfYear. So define the projection:

Func<DateTime, int> weekProjector = 
    d => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
         d,
         CalendarWeekRule.FirstFourDayWeek,
         DayOfWeek.Sunday);

You can configure exactly how the “week number” is determined by tweaking the parameters in the method call. You can also decide to define the projection as e.g. an extension method if you prefer; this does not change the essence of the code. In any case, you are then ready to group by week:

var consignmentsByWeek = from con in consignments
                         group con by weekProjector(con.Date);

If you also want to constrain the output to consigments between two specific dates, just add an appropriate where clause; the grouping logic does not change.

Leave a Comment

tech