如何将此转换为使用Linq到数据集?
foreach (Row row in Rows)
{
if (row.material> 0)
sumtid += row.time * row.material;
else
sumtid += row.time;
}
答案 0 :(得分:7)
var sumtid = Rows.Sum(x => x.time * (x.materials > 0 ? x.materials : 1));
或
var sumtid = Rows.Sum(x => x.materials > 0 ? x.time * row.materials : x.time);
我假设您的Rows
变量为IEnumerable<Row>
。
修改强> 的
解决问题的另一种方法:
var sumtid = Rows.Select(x => x.materials > 0 ? x.time * row.materials : x.time)
.Sum();
答案 1 :(得分:2)
除了@ MarcinJuraszek的回答,您还可以按原样使用您的代码:
var sumtid = Rows.Sum(row =>
{
if (row.material> 0)
return row.time * row.material;
else
return row.time;
});