2

如何将其转换为使用 Linq 到数据集?

foreach (Row row in Rows) 
{ 
    if (row.material> 0) 
        sumtid += row.time * row.material; 
    else 
        sumtid += row.time; 
} 
4

2 回答 2

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();
于 2013-10-21T05:16:25.787 回答
2

除了@MarcinJuraszek 的回答,您还可以按原样使用您的代码:

var sumtid = Rows.Sum(row =>
    {
        if (row.material> 0) 
            return row.time * row.material; 
        else 
            return row.time; 
    });
于 2013-10-21T05:19:17.633 回答