Lambda expression in 'if' statement condition

.net, c#, lambda

Solution

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

Problem

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.

Original source