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.
I don't think there's an elegant way to do it when using the ForEach method. A hacky solution is to throw an exception.
What's preventing you from doing an old fashioned foreach?
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.Note that the above will still iterate through each item but return immediately. Of course, this way is probably not as good as a normal
foreach
.Would this work for you: