Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use continue statement in .ForEach() method

Is there an equivalent to the continue statement in ForEach method?

List<string> lst = GetIdList(); lst.ForEach(id => {      try      {        var article = GetArticle(id);        if (article.author.contains("Twain"))        {          //want to jump out of the foreach now          //continue; **************this is what i want to do*******         }         //other code follows    } 

EDIT: Thanks for all the great answers. And thank you for the clarification that .foreach is not an extension method. I use this structure to keep the coding style consistent (a different programmer worked on another similar method in the same class)...and thanks for the links to why to avoid using .foreach.

like image 378
Laguna Avatar asked Nov 30 '11 21:11

Laguna


People also ask

Can I use continue in forEach Java?

continue inside loop is not supported by forEach. As a workaround you can return from the loop.

How do you continue a stream in forEach?

How to write continue statement inside forEach loop in java 8. A lambda expression is almost equivalent of instance of an anonymous class. Each iteration will call the overridden method in this instance. So if you want to continue, just return the method when condition is met.

Can we use break and continue in forEach loop in JavaScript?

No, it doesn't, because you pass a callback as a return, which is executed as an ordinary function. All forEach does is call a real, actual function you give to it repeatedly, ignore how it exits, then calls it again on the next element.

Can we use break statement in forEach loop?

Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.


2 Answers

A) ForEach is not LINQ, it is a method on List<T>.
B) Just use foreach.
C) return will do it.

Edit

Just to clarify, what you are doing is providing a method that will be called for each entry in the list. return will just apply to the method for that member. The rest of the members in the list will still call the method.

like image 164
cadrell0 Avatar answered Sep 28 '22 03:09

cadrell0


Personally, I would just use a standard foreach loop instead of List<T>.ForEach.

In this case, you can invert the condition (to avoid the code in that case) or call return, since your goal is to use a continue statement. However, if you wanted to break, this would not work. That being said, there are quite a few other reasons to avoid List<T>.ForEach, so I would consider switching this to a normal foreach statement.

like image 44
Reed Copsey Avatar answered Sep 28 '22 02:09

Reed Copsey