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.
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.
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.
Continue is not the opposite of break , break stops the loop, continue stops the current iteration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With