ForEach() : Why can't use break/continue inside
Solution 1
Because ForEach
is a method and not a regular foreach
loop. The ForEach
method is there for simple tasks, if you need to break or continue just iterate over lstTemp
with a regular foreach
loop.
Usually, ForEach
is implemented like this:
public static ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
foreach(var i in input)
action(i);
}
As it is a normal method call, action
doesn't know anything about the enclosing foreach
, thus you can't break.
Solution 2
return
will act as continue
in ForEach
.
Example:
var list = new List<int>() {1, 2, 3, 4};
list.ForEach(i =>
{
if (i == 3)
return;
Console.WriteLine(i);
}
);
Prints 1, 2, 4.
3 - skipped.
Solution 3
Presumably because you're using a lambda and the contents of the lambda are ignorant to the fact that it's being used inside a loop.
Solution 4
rather than using a break, perform a filter first like this (it may not be the exact filter you need, but illustrates the point)
lstTemp.Where(i => i!= 3).ForEach(i=> // do sth);
Solution 5
To iterate only part of the items and emulate the break perfectly, you can use FirstOrDefault
:
lstTemp.FirstOrDefault(i=>
{
if (i == 3)
return true;
//do stuff
return false;
}
);
For list with 100000 items, if the 10th item is 3 it will iterate only 10 times, using the Where
solution will work, but iterate the whole list first.
Related videos on Youtube
Rami Alshareef
Experienced and enthusiast Full Stack Software Engineer with passion toward best practices, collaborative work, Agile culture, clean code, and software architecture. Experienced with all stages of software development including QA and DevOps. I enjoy aligning business needs with software engineering and always seek to expand my engineering area of expertise and influence . Forward thinker and strategic planner, with aptitude for learning new skills. Team oriented with hands on scrum values and practices. It is a true privilege and beyond rewarding to work at a place that influences thousands of developers around the world. Rami's experiences include but are not limited to: • Scrum, Agile framework, and collaborative work • Restful & web api, Solid OOP, DevOps • Software architecture, design, development, deployment process, and QA • Research and implementation • Database architecture and design
Updated on July 09, 2022Comments
-
Rami Alshareef almost 2 years
Since ForEach() method loop through all a list members, Why cant 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"
-
Tesserex over 13 yearsA well written ForEach extension should allow you to return false if you want it to break. But I can't say for sure since I don't know where you got your foreach. If you wrote it yourself that may be a good option.
-
Juliet over 13 yearsLooks like you want the TakeWhile function msdn.microsoft.com/en-us/library/bb534804%28v=VS.90%29.aspx
-
CS Smit about 9 yearsI found a better answer here: stackoverflow.com/questions/3145563/list-foreach-break
-
-
Sergio over 13 years-1 Not the samething. your code will run for every i != 3. The code presented will run until i == 3.
-
James Gregory over 13 yearsThe
Where
method does not iterate the collection, see: deferred execution. -
Shadow The Kid Wizard over 13 years@James maybe iterate isn't the right word.. but to find all matching items, somewhere somehow all items must be checked, isn't it?
-
James Gregory over 13 yearsHave a read of how the
yield
keyword works, because that's how LINQ queries operate. It's too long to explain here, but no, not all the items must be checked; only as many items as are requested by the call-chain will be checked. Exactly the same as yourFirstOrDefault
, which will iterate until it hits a match. -
Nigiri almost 11 yearsThis seems the best way for 'continue'. Besides we can just write 'return' for 'break'.
-
Lance almost 11 yearsGiven that it's a method call, can I just return instead of break?
-
Femaref almost 11 yearsNo, you will just return from the method itself. You will not be able to break out of an outer foreach that way.
-
Rafael over 10 yearsthis doesn't exactly answer the question. OP is asking why he/she can't use break/continue like a normal loop.
-
code4life about 7 yearsTry removing the
do-while
and use thebreak
, LOL.