I am writing an Excel exporter for a bespoke application I am creating, and I have a question about LINQ grouping in C#.
Basically, this new Excel exporter class is
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 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.