Group list by month
Asked Answered
B

2

15

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 ?

Bridesmaid answered 28/4, 2015 at 19:28 Comment(1)
Not an answer, but based on your example you are also grouping based on the year rather than just the month.Rufescent
I
34

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.

Illfated answered 28/4, 2015 at 19:30 Comment(1)
will this not combine the years?Coulisse
P
-1
    myList
   .GroupBy(x => new {MonthYear = x.myDate.Month + "-" + x.myDate.Year})
   .Select(x => new { x.Key.MonthYear });
Porche answered 1/12, 2022 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.