Reputation: 913
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
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
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