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

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.


There is no loop that one has access to, from which to break. And each call to the (anonymous) delegate is a new function call so local variables will not help. But since C# gives you a closure, you can set a flag and then do nothing in further calls:

bool stop = false;
myList.ForEach((a) => {
  if (stop) {
    return;
  } else if (a.SomeCondition()) {
    stop = true;
  }
});

(This needs to be tested to check if correct reference semantics for closure is generated.)

A more advanced approach would be to create your own extension method that allowed the delegate to return false to stop the loop:

static class MyExtensions {
  static void ForEachStoppable<T>(this IEnumerable<T> input, Func<T, bool> action) {
    foreach (T t in input) {
      if (!action(t)) {
        break;
      }
    }
  }
}

Do you have LINQ available to you? Your logic seems similar to Any:

bool any = blackList.Any(s=>inputString.Contains(s));

which is the same as:

bool any = blackList.Any(inputString.Contains);

If you don't have LINQ, then this is still the same as:

bool any = blackList.Find(inputString.Contains) != null;

If you want to run additional logic, there are things you can do (with LINQ) with TakeWhile etc