Consider this
List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6 };
int j = 0;
intList.ForEach(i =>
{
if (i.Equals(1))
{
j = i;
break;
}
}
);
Throwing error: No enclosing loop out of which to break or continue
But the below works
foreach(int i in intList)
{
j = i; break;
}
Why so. Am I making any mistake.
Thanks
Keep in mind that the purpose of the ForEach method is to call the lambda method you pass to it on each item in the list. If you need to break out of a loop as part of your loop processing, you have to use a classic loop.
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