简体   繁体   English

Linq按日期分组(月份)

[英]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) . 例如,我有一个MyObjects(DateTimeField, AmountField)列表MyObjects(DateTimeField, AmountField) I want to group by DateTimeField , but not entire date, just by month, and then sum the AmountField for each month. 我想按DateTimeField分组,但不是整个日期,只是按月AmountField ,然后将每月的AmountField相加。

I don't know why the objectgrouped is null? 我不知道为什么objectgrouped是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

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): 将空值放在一个单独的存储桶中(“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) 
                         });

Try this: 试试这个:

List<DateTime> list = new List<DateTime>();
var grouppedResult = list.GroupBy(x => x.Month);
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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM