Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List ForEach break

Tags:

c#

foreach

break

is there a way to break out of the foreach extension method? The "break" keyword doesn't recognize the extension method as a valid scope to break from.

//Doesn't compile
Enumerable.Range(0, 10).ToList().ForEach(i => { System.Windows.MessageBox.Show(i.ToString()); if (i > 2)break; });

Edit: removed "linq" from question


note the code is just an example to show break not working in the extension method... really what I want is for the user to be able to abort processing a list.. the UI thread has an abort variable and the for loop just breaks when the user hits a cancel button. Right now, I have a normal for loop, but I wanted to see if it was possible to do with the extension method.

like image 643
tbischel Avatar asked Jun 29 '10 23:06

tbischel


People also ask

Can we use break in forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

How do you break out of a forEach?

To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection. Copied!

Can we break forEach in C#?

We can break multiple for / for each loop using break, //We can break multiple for /for each loop using break. bool BreakAllLoops = false; for (int i = 0; i < 10; i++)

How do you break a forEach loop in angular 9?

Use every() instead of forEach() every(v => { if (v > 3) { return false; } console. log(v); // Make sure you return true. If you don't return a value, `every()` will stop. return true; });


1 Answers

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;}
    });
like image 171
JaredPar Avatar answered Oct 17 '22 08:10

JaredPar