ForEach() : Why can't use break/continue inside

39,736

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.

Share:
39,736

Related videos on Youtube

Rami Alshareef
Author by

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 &amp; web api, Solid OOP, DevOps • Software architecture, design, development, deployment process, and QA • Research and implementation • Database architecture and design

Updated on July 09, 2022

Comments

  • Rami Alshareef
    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"

  • Sergio
    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
    James Gregory over 13 years
    The Where method does not iterate the collection, see: deferred execution.
  • Shadow The Kid Wizard
    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
    James Gregory over 13 years
    Have 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 your FirstOrDefault, which will iterate until it hits a match.
  • Nigiri
    Nigiri almost 11 years
    This seems the best way for 'continue'. Besides we can just write 'return' for 'break'.
  • Lance
    Lance almost 11 years
    Given that it's a method call, can I just return instead of break?
  • Femaref
    Femaref almost 11 years
    No, you will just return from the method itself. You will not be able to break out of an outer foreach that way.
  • Rafael
    Rafael over 10 years
    this doesn't exactly answer the question. OP is asking why he/she can't use break/continue like a normal loop.
  • code4life
    code4life about 7 years
    Try removing the do-while and use the break, LOL.