Linq Grouping by Date (month)

19,451

Solution 1

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

Solution 2

Try this:

List<DateTime> list = new List<DateTime>();
var grouppedResult = list.GroupBy(x => x.Month);

Solution 3

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();
Share:
19,451
user2112420
Author by

user2112420

Updated on June 15, 2022

Comments

  • user2112420
    user2112420 almost 2 years

    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