Group list by month

╄→гoц情女王★ 提交于 2019-12-12 10:37:31

问题


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 example: Before grouping [mix below elements]

After grouping: 1) January 2015 - 5 elements 2) February 2015 - 2 elements 2) January 2014 - 2 elements

I have tried like this:

var test = this.myList.GroupBy(x => x.myDate.Month).ToList();

But iI thnink I need to use dictionary. Do you have any ideas how to solve it ?


回答1:


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.



来源:https://stackoverflow.com/questions/29928233/group-list-by-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!