Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list by month

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 ?

like image 539
mskuratowski Avatar asked Apr 28 '15 19:04

mskuratowski


People also ask

How to Group A SharePoint list based on month name and year?

Sharepoint custom list data can be easily grouped on any column of our choice. We had a requirement to group a custom list based on Month Name and year from a date column for which we had to create a calculated column and tweak it. This blog explains how this was achieved 1. Create a new calculated column in the Sharepoint list.

How to group date by month in pivot table?

Group date by month, quarter or year in pivot table There is a Group function in pivot table, you can apply it to group data as your need. 1. Select the data range you need, and click Insert > PivotTable.

How to use group by month in SQL?

Month value can be retrieved from the date-time data typed column using the SQL function MONTH (). This is done mostly for building queries for reports. This is a guide to the SQL GROUP BY Month. Here we discuss the Introduction, syntax, and examples with code implementation respectively.

What is the syntax of the group by month clause?

The syntax of the group by month clause is as follows – The syntax of the GROUP BY clause is as shown above. It is the optional clause used in the select clause whenever we need to summarize and reduce the resultset. It should always be placed after the FROM and WHERE clause in the SELECT clause.


1 Answers

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.

like image 190
Andrei Avatar answered Oct 05 '22 10:10

Andrei