Using break alone will not work here because lambda is executed in a different method than the for loop. The break statement is only useful for exiting constructs that are local to the current function.
To maintain a stylish break style, you need to add a ForEach overload where the delegate can specify through the return value that should be executed when the loop is executed. for instance
public static void ForEach<T>(this IEnumerable<T> enumerable, Func<T, bool> func) { foreach (var cur in enumerable) { if (!func(cur)) { break; } } }
Now, the consumer of this ForEach method can specify break , returning false from the provided callback
myCollection.ForEach(current => { if (someCondition) { // Need to break return false; } // Keep going return true; }
source share