if i have this code today to find out a sum total using LINQ:
return (MyArray.Sum(r => r.Trips);
and i want to only include itms where r.CanDrive == true.
can you add a condition into a single linke lambda expression? how would you do this
if i have this code today to find out a sum total using LINQ:
return (MyArray.Sum(r => r.Trips);
and i want to only include itms where r.CanDrive == true.
can you add a condition into a single linke lambda expression? how would you do this
You could chain two bits of LINQ together like so:
return MyArray.Where(r => r.CanDrive).Sum(r => r.Trips);
David's answer is entirely correct, but another alternative might be to use a conditional operator:
return MyArray.Sum(r => r.CanDrive ? r.Trips : 0);
I would personally use the Where
form, but I thought I'd present an alternative...
(Yet another alternative would be to create your own Sum
method which took both a predicate and a projection, but I think that's over the top.)