4

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
ekad
  • 14,436
  • 26
  • 44
  • 46
user2112420
  • 955
  • 5
  • 11
  • 26

3 Answers3

6

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) 
                         });
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • No, just the month, because before I get all the data from the current year. But I cant do DateTime.Month, I think is because it is a Nullable, what could I do? Thanks – user2112420 Apr 12 '13 at 19:56
  • How do you want to handle null values? Do they go in their own bucket or are they ignored? – D Stanley Apr 12 '13 at 19:57
  • It is just a Model and DataBase thing, but it is always not null on the DB. – user2112420 Apr 12 '13 at 19:59
2

Try this:

List<DateTime> list = new List<DateTime>();
var grouppedResult = list.GroupBy(x => x.Month);
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
1
var groups = list.GroupBy(l => l.DateTimeField.Year * 12 + l.DateTimeField.Month)
                .Select(g => new {
                                Month=g.First().DateTimeField,
                                Sum=g.Select(a=>a.AmountField).Sum() 
                             })
                .ToList();
I4V
  • 34,891
  • 6
  • 67
  • 79