我想知道如何按月分组一些数据并求和字段。例如,我有一个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
我想你说的"month"是指"month and year":
忽略空值:
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)
});
试试这个:
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();