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
Using if-else in lambda function Here, if block will be returned when the condition is true, and else block will be returned when the condition is false. Here, the lambda function will return statement1 when if the condition is true and return statement2 when if the condition is false.
In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.
In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With