C # exit generic ForEach that use lambda

Does anyone know if it's possible to get out of universal ForEach using lambda? eg.

someList.ForEach(sl => { if (sl.ToString() == "foo") break; // continue processing sl here // some processing code } ); 

This code itself will not compile. I know I can use regular foreach, but for consistency I want to use lambda.

Many thanks.

+7
generics c # lambda foreach break
source share
4 answers

Of course. But first, note that I recommend against this; I say that the sequence operator should not have a side effect, and the operator should have a side effect. If you are doing something in this ForEach lambda, make this statement in the body of the foreach loop, rather than making it look like a sequence statement.

So here is what you do. First, you write yourself ForEach, which runs on arbitrary sequences, not just lists:

 public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) { foreach(var item in sequence) action(item); } 

And now you write your break as follows:

 someList .TakeWhile(x=>x.ToString() != "foo") .ForEach(sl=> {/*your action here*/}); 
+17
source share

From MSDN

The following domain rules in lambda expressions belong to a variable:

snip

A lambda expression cannot contain a goto statement, a break or continue statement whose purpose is to use an anonymous function inside the body or in the body.

I don't know if this code helps in the code you posted. The corresponding quote is at the end of the MSDN article.

+7
source share

Warning: the code below should not be taken seriously and is provided for entertainment purposes only!

You can "simulate" a continuation with an early return like this:

 Enumerable.Range(1, 20) .ForEach(n => { if (n == 10) return; Console.WriteLine("This is not 10: {0}", n); }); 

However, I think that side effects in lambda are a sign that you are doing it wrong. Use the correct foreach instead. Or something like TakeWhile, as Eric kindly demonstrated.

+1
source share

How about this?

  Enumerable.Range(1, 10) .Where(x => x % 2 != 0) .ToList() .ForEach(x => Console.WriteLine(x)); 
0
source share

All Articles