How to group dates by week?

后端 未结 4 1547
死守一世寂寞
死守一世寂寞 2020-12-15 04:18

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

4条回答
  •  太阳男子
    2020-12-15 05:17

    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.

提交回复
热议问题