Cornel Marian
Cornel Marian

Reputation: 2503

How do I convert this to using Linq to dataset?

How do I convert this to using Linq to dataset?

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

Upvotes: 2

Views: 62

Answers (2)

lc.
lc.

Reputation: 116458

In addition to @MarcinJuraszek's answer, you can also use your code as is:

var sumtid = Rows.Sum(row =>
    {
        if (row.material> 0) 
            return row.time * row.material; 
        else 
            return row.time; 
    });

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

var sumtid = Rows.Sum(x => x.time * (x.materials > 0 ? x.materials : 1));

or

var sumtid = Rows.Sum(x => x.materials > 0 ? x.time * row.materials : x.time);

I've assumed your Rows variable is IEnumerable<Row>.

Edit

Another way of solving the problem:

var sumtid = Rows.Select(x => x.materials > 0 ? x.time * row.materials : x.time)
                 .Sum();

Upvotes: 7

Related Questions