我想根据另一列在列表集合中汇总一列。
这就是班级的样子
Date Payment
2015-09-09 500
2015-09-09 200
2017-01-03 150
2017-01-03 300
结果应该是这样的
Date Payment
2015-09-09 700
2017-01-03 450
代码:
var result = from e in scheduleDetails
let k = new
{
Date = e.ActualDueDate
}
group e by k into t
select new
{
Date = t.Key.Date,
Payment = t.Sum(e => e.EscrowPayment)
};
List<ScheduleDetails> temp = result.Select(t => new ScheduleDetails(t.Date, t.Payment)).ToList();
我不希望创建匿名类型,因此我将其映射到原始对象。为此,我必须创建构造函数。
public ScheduleDetails(DateTime? date, decimal? payment)
{
this.ActualDueDate = date;
this.EscrowPayment = payment;
}
问题:
答案 0 :(得分:1)
您无需创建新的范围变量和匿名类型:
var temp = scheduleDetails.GroupBy(sd => sd.ActualDueDate)
.Select(g => new ScheduleDetails(g.Key, g.Sum(sd => sd.EscrowPayment)))
.ToList();
此外,如果ScheduleDetails
类为其ActualDueDate
和EscrowPayment
属性设置了公共设置器,则可以在不添加构造函数的情况下使用对象初始值设定项:
.Select(g => new ScheduleDetails {
ActualDueDate = g.Key,
EscrowPayment = g.Sum(sd => sd.EscrowPayment)
})
查询语法(请注意,此处的临界值为IEnumerable<ScheduleDetails>
):
var temp = from sd in scheduleDetails
group sd by sd.ActualDueDate into g
select new ScheduleDetails {
ActualDueDate = g.Key,
EscrowPayment = g.Sum(sd => sd.EscrowPayment)
};