Group list by month

前端 未结 1 2107
广开言路
广开言路 2021-02-20 02:22

I have list with datetime objects. I would like to group by month and add it to the dictionary.

So after grouping process I want to have list per month and year. For e

1条回答
  •  灰色年华
    2021-02-20 02:27

    Linq provides an option to convert your results into a dictionary:

    myList.GroupBy(x => new {Month = x.myDate.Month, Year = x.myDate.Year})
          .ToDictionary(g => g.Key, g => g.Count())
    

    Note that this will give you keys in form of {Month=1,Year=2015}. If you want a string instead, something like January 2015, you can use formatted date string as a key.

    0 讨论(0)
提交回复
热议问题