Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Grouping by Date (month)

I would like to know how I could group some data by month and sum a field. For example I have a list of MyObjects(DateTimeField, AmountField). I want to group by DateTimeField, but not entire date, just by month, and then sum the AmountField for each month.

I don't know why the objectgrouped is null?

    IEnumerable<MyObject> objectList= GetMyObject();

    var ObjectGrouped = objectList.GroupBy(l => l.ObjectDate.GetValueOrDefault().Month)
                          .Select(lg =>
                                new
                                {
                                    CurrentMonth = lg.Key,
                                    Total = lg.Sum(w => w.ObjectAmount)
                                });

ObjectDate      ObjectAmount

1/1/2013              3.3
3/1/2013              6.9
13/2/2013            5
3/4/2013              3.6
13/4/2013            15.2
like image 790
user2112420 Avatar asked Jan 14 '23 16:01

user2112420


2 Answers

I assume by "month" you mean "month and year":

To ignore null values:

var query = myList.Where(i => i.DateTimeField.HasValue)
                  .GroupBy(i => i.DateTimeField.Value.Month)
                  .Select(g => new {
                            Month=g.Key,
                            Total=g.Sum(i=>i.AmountField) 
                         });

to put null values in a separate bucket ("0" month):

var query = myList.GroupBy(i => i.DateTimeField.HasValue ? i.DateTimeField.Value.Month : 0)
                  .Select(g => new {
                            Month=g.Key,
                            Total=g.Sum(i=>i.AmountField) 
                         });
like image 188
D Stanley Avatar answered Jan 19 '23 01:01

D Stanley


Try this:

List<DateTime> list = new List<DateTime>();
var grouppedResult = list.GroupBy(x => x.Month);
like image 44
Nikolay Kostov Avatar answered Jan 19 '23 00:01

Nikolay Kostov