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.
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.