Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you add a condition to a lambda expression

Tags:

arrays

c#

linq

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

like image 552
leora Avatar asked Jun 07 '10 10:06

leora


People also ask

How do you write if-else in lambda function in Python?

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.

What does => mean in lambda?

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.

Can we use dynamic in lambda expression?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.


2 Answers

You could chain two bits of LINQ together like so:

return MyArray.Where(r => r.CanDrive).Sum(r => r.Trips);
like image 179
David M Avatar answered Oct 20 '22 18:10

David M


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.)

like image 33
Jon Skeet Avatar answered Oct 20 '22 18:10

Jon Skeet