按月份分组 [英] Group list by month
问题描述
我有日期时间对象的列表。我想按月分组并将其添加到字典中。
因此,在分组过程之后,我希望每月和每年都有列表。
例如:
在分组
之前[在元素下面混合]
分组后:
1)2015年1月 - 5元素
2)2015年2月 - 2个元素
2)2014年1月 - 2个元素
我试过这样:
var test = this.myList.GroupBy(x => x.myDate.Month).ToList();
但是我需要使用字典。你有什么想法如何解决它?
Linq提供了一个选项来将结果转换为字典:
myList.GroupBy(x => new {Month = x.myDate.Month,Year = x.myDate.Year})
.ToDictionary(g => g.Key,g => g.Count())
<请注意,这将为您提供 {月= 1,年= 2015}
形式的密钥。如果你想要一个字符串,比如 January 2015
,你可以使用格式化的日期字符串作为键。
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 ?
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.
这篇关于按月份分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!