我想知道如何按月对一些数据进行分组并对一个字段求和。
例如,我有一个 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
最佳答案
我假设“月”是指“月和年”:
忽略空值:
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)
});
关于c# - Linq 按日期分组(月),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15979462/