Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i exit a List<string>.ForEach loop when using an anonymous delegate?

In a normal loop you can break out of a loop using break. Can the same be done using an anonymous delegate?

Example inputString and result are both declared outside the delegate.

blackList.ForEach(new Action<string>(     delegate(string item)     {         if(inputString.Contains(item)==true)         {             result = true;             // I want to break here         }     } )); 

Edit: Thanks for the replies, I'm actually reading your book at the minute John :) Just for the record i hit this issue and switched back to a normal foreach loop but I posted this question to see if i missed something.

like image 315
SecretDeveloper Avatar asked Feb 17 '09 14:02

SecretDeveloper


People also ask

How do I break out of nested forEach?

The only way to this directly is with a goto . Another (better) option is to restructure until the problem goes away. For instance by putting the inner code (while + foreach) in a method and use return to get back.

How do you exit a forEach loop in C#?

Exit Foreach Loop Using break Keyword In C# Let's say you have a list of colors or an array of colors and you are looping through the list and now you have to exit the foreach loop, you will use the break keyword to exit the loop.

Does continue break out of forEach loop?

Continue is not the opposite of break , break stops the loop, continue stops the current iteration.


1 Answers

As others have posted, you can't exit the loop in ForEach.

Are you able to use LINQ? If so, you could easily combine TakeWhile and a custom ForEach extension method (which just about every project seems to have these days).

In your example, however, List<T>.FindIndex would be the best alternative - but if you're not actually doing that, please post an example of what you really want to do.

like image 78
Jon Skeet Avatar answered Oct 11 '22 01:10

Jon Skeet