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.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With