如何将其转换为使用 Linq 到数据集?
foreach (Row row in Rows)
{
if (row.material> 0)
sumtid += row.time * row.material;
else
sumtid += row.time;
}
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();
除了@MarcinJuraszek 的回答,您还可以按原样使用您的代码:
var sumtid = Rows.Sum(row =>
{
if (row.material> 0)
return row.time * row.material;
else
return row.time;
});