4

我想知道如何按月对一些数据进行分组并对一个字段求​​和。例如,我有一个MyObjects(DateTimeField, AmountField). 我想按月分组DateTimeField,但不是整个日期,然后AmountField按月汇总。

我不知道为什么objectgrouped是空的?

    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
4

3 回答 3

6

我假设“月”是指“月和年”:

要忽略空值:

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

将空值放入单独的存储桶(“0”月):

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) 
                         });
于 2013-04-12T19:48:42.030 回答
2

尝试这个:

List<DateTime> list = new List<DateTime>();
var grouppedResult = list.GroupBy(x => x.Month);
于 2013-04-12T19:34:04.923 回答
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();
于 2013-04-12T19:44:14.767 回答