Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression in 'if' statement condition

Tags:

c#

.net

lambda

I am new to C#, but from my understanding this code should work. Why doesn't it work?

This is an example of my code.

List<Car> cars // This has many cars initialized in it already
if (() => {
   foreach(Car car in cars){
       if (car.door == null) return true;
   }
}){then .......}

Simply put, all I want the code to do is run the if statement if any car does not have a door.

After trying to compile I get this error:

Cannot convert lambda expression to type 'bool' because it is not a delegate type.

like image 261
user3813249 Avatar asked Jul 07 '14 16:07

user3813249


2 Answers

If you want to check if any car does not have a door then simply use Enumerable.Any - it determines whether any element of a sequence satisfies a condition:

if (cars.Any(c => c.door == null))
   // then ...

Just for fun: you should execute lambda to get boolean result in if condition (but for this case use Any)

Func<bool> anyCarDoesNotHaveDoor = () => { 
    foreach(var car in cars)
       if (car.door == null)
           return true;
    return false; 
};

if (anyCarDoesNotHaveDoor())
   // then ...

I introduced local variable to make things more clear. But of course you can make this puzzle more complicated

 if (new Func<bool>(() => { 
        foreach(var car in cars)
           if (car.door == null)
               return true;
        return false; })())
    // then ...    
like image 120
Sergey Berezovskiy Avatar answered Sep 20 '22 17:09

Sergey Berezovskiy


Well, the error says it all. An if statement is expecting a boolean expression which a delegate is not. If you were to call the delegate (assuming it returned a bool), you would be fine. However, if does not know to call it.

The easy way to do this is with the Any LINQ extension method:

if (cars.Any(car => car.door == null))

The Any method knows to actually invoke the lambda expression on each member of the collection, and returns a bool. This makes it a valid boolean expression for the if statement.

like image 32
BradleyDotNET Avatar answered Sep 20 '22 17:09

BradleyDotNET