Linq Grouping by Date (month)

user2112420 picture user2112420 · Apr 12, 2013 · Viewed 19k times · Source

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

Answer

D Stanley picture D Stanley · Apr 12, 2013

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) 
                         });