我有以下代码,我想将for eaches转换为一个linq语句
decimal originalCharges = 0;
List<int> rdns = new List<int>()
{
1,
2
};
foreach (var customerOrder in list)
{
foreach (CustomerBillTo billTo in customerOrder.BillTos)
{
originalCharges += billTo.Charges
.Where(charge => rdns.Contains(charge.RateCodeRdn))
.Sum(charge => charge.Amount);
}
}
这是我到目前为止所尝试的
originalCharges = list.ForEach(co => co.BillTos.ForEach(bt => bt.Charges.Where(charge => rdns.Contains(charge.RateCodeRdn)).Sum(charge => charge.Amount)));
哪个给我一个错误,无法将类型“void”转换为“十进制”。
我认为我对第一个示例中的原始forEach循环中使用+ = for originalCharges感到困惑。
这可以在linq声明中完成吗?
originalCharges = list.ForEach(co => co.BillTos.ForEach( ));
答案 0 :(得分:0)
你只需投射并压平收费金额并总结起来。
var originalCharges =
(from customerOrder in list
from billTo in customerOrder.BillTos
from charge in billTo.Charges
where rdns.Contains(charge.RateCodeRdn)
select charge.Amount).Sum();
或者如果您更喜欢流利的方法:
var originalCharges =
list.SelectMany(customerOrder =>
customerOrder.BillTos.SelectMany(billTo =>
billTo.Charges
.Where(charge => rdns.Contains(charge.RateCodeRdn))
.Select(charge => charge.Amount)
)
).Sum();