It's probably more accurate to call this a List<T>
Foreach vs. a LINQ one.
In either case though no there is no way to break out of this loop. Primarily because it's not actually a loop per say. It's a method which takes a delegate that is called inside a loop.
Creating a ForEach with break capability is fairly straight forward though
public delegate void ForEachAction<T>(T value, ref bool doBreak);
public static void ForEach<T>(this IEnumerable<T> enumerable, ForEachAction<T> action) {
var doBreak = false;
foreach (var cur in enumerable) {
action(cur, ref doBreak);
if (doBreak) {
break;
}
}
}
You could then rewrite your code as the following
Enumerable.Range(0,10)
.ForEach((int i,ref bool doBreak) => {
System.Windows.MessageBox.Show(i.ToString());
if ( i > 2) {doBreak = true;}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…