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.
continue inside loop is not supported by forEach. As a workaround you can return from the loop.
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.
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.
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.
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.
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.
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