0

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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What does it return? a bool? Do I need to handle null?
Yes, it returns a bool, No there is no null to handle here
even if I pass an empty List?
Yes, if you use an empty list then the result will be false
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.