Since ForEach() method loop through all list members, Why can’t I use a break/continue clause while I can use them inside a normal foreach loop
lstTemp.ForEach(i=>
{
if (i == 3)
break;
//do sth
}
);
Error:
"No enclosing loop out of which to
break or continue"
Because
ForEachis a method and not a regularforeachloop. TheForEachmethod is there for simple tasks, if you need to break or continue just iterate overlstTempwith a regularforeachloop.Usually,
ForEachis implemented like this:As it is a normal method call,
actiondoesn’t know anything about the enclosingforeach, thus you can’t break.