简体   繁体   中英

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.

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.

Just invert your if condition:

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

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.

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.

Continue in a foreach will loop back up to the top of the loop to the next item in the sequence. If that's what you want, return should do it. If you want to exit entirely, you may want to rewrite it using an actual LINQ method like Any().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM