Tlink
Tlink

Reputation: 913

statements and return within a lambda expression lambda

In C# I'm trying to verify if a buss full of passengers is ready to go by verifying the passengers payments:

bool busReadyToGo = true;
passengers.Any(p => p.paymentStatus == PaymentRegistryEnum.NotPaid ?  busReadyToGo = false; return busReadyToGo; : continue; );

So this should check all the passengers payment status, if it encounters one passenger that hasn't paid then it stops right there and returns busReadytoGo = false. otherwise it continues iterating/filtering passengers, which means it will later return true if a passenger hasn't paid.

Not sure if this is the right way to do this within the Linq/lambda expression, because I keep getting syntax errors.

Upvotes: 0

Views: 54

Answers (2)

sekky
sekky

Reputation: 834

The method .Any will already return a bool value. There is no need to include an if-Statement in the expression. This should do just fine:

bool busReadyToGo = !passengers.Any(p => p.paymentStatus == PaymentRegistryEnum.NotPaid)

Upvotes: 2

Steve
Steve

Reputation: 216293

Any already stops its enumeration when it meets the first element that returns true in the lambda expression. You just need to get the result from Any

busReadyToGo = !passengers.Any(p => p.paymentStatus == PaymentRegistryEnum.NotPaid);

If you look at the Remarks section in docs you can read

The enumeration of source is stopped as soon as the result can be determined.

Upvotes: 2

Related Questions