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

Laguna picture Laguna · Nov 30, 2011 · Viewed 31.6k times · Source

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.

Answer

cadrell0 picture cadrell0 · Nov 30, 2011

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.