ZNackasha
ZNackasha

Reputation: 1089

Lambda expression in 'if' statement condition

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.

Upvotes: 14

Views: 20195

Answers (3)

BradleyDotNET
BradleyDotNET

Reputation: 61339

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.

Upvotes: 9

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

In case you want to actually do something to cars without doors:

foreach (var car in cars.Where(car => car.door == null)) {
    car.door = <whatever>;
}

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

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

Upvotes: 35

Related Questions