Using break alone won't work here because the lambda executes in a different method than the for loop. A break statement is only useful for breaking out of constructs local to the current function.
In order to support a break style leave you'd need to add an overload of ForEach where the delegate can specify via a return value that loop execution should break. For example
public static void ForEach<T>(this IEnumerable<T> enumerable, Func<T, bool> func) {
foreach (var cur in enumerable) {
if (!func(cur)) {
break;
}
}
}
Now a consumer of this ForEach method can specify a break by returning false from the provided callback
myCollection.ForEach(current => {
if (someCondition) {
// Need to break
return false;
}
// Keep going
return true;
}
answered 2012-01-30T20:12:03.190