tags:

views:

96

answers:

2

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

+12  A: 

You could chain two bits of LINQ together like so:

return MyArray.Where(r => r.CanDrive).Sum(r => r.Trips);
David M
What's with the leading parenthesis?
Codesleuth
@Codesleuth - fat fingers! Thanks...
David M
@David M. Your dialing wand is in the post :)
MPritch
+8  A: 

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

Jon Skeet