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

35,993

Solution 1

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.

Solution 2

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.

Solution 3

Just invert your if condition:

lst.ForEach(id => {
                      var article = GetArticle(id);
                      if (!article.author.contains("Twain"))
                      {
                          // other code here
                      }
                  });

Solution 4

The method you're using is List<T>.ForEach, a method defined on the class and not a LINQ extension method. This question actually has nothing to do with LINQ.

return; in the delegate passed to List<T>.ForEach should approximate using continue; in an actual foreach construct.

Solution 5

To answer your question:

List<string> lst = GetIdList();
lst.ForEach(id =>
{
    try
    {
        var article = GetArticle(id);
        if (article.author.contains("Twain"))
            goto _continue;
    }

    //other code follows

    _continue:;
}

The other answers are right, avoid .ForEach().
goto should be avoided as well, although it's sometimes useful for shortcutting code blocks.

Share:
35,993
Laguna
Author by

Laguna

I write C# in Atlanta, US. http://www.linkedin.com/in/wenyi If you are really bored: http://wenyiwu.wordpress.com/

Updated on March 02, 2021

Comments

  • Laguna
    Laguna about 3 years

    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.

  • SQLMason
    SQLMason over 12 years
    +1 because it's the same answer as the selected answer but 1 minute earlier.