Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulate break statement in ForEach function

Tags:

c#

lambda

This is more of a hypothetical question as I am using .NET 3.5 more and more along with lambda expressions and anonymous delegates. Take this simple example:

static void Main(string[] args)
{
   List<int> numList = new List<int>(int[] { 1, 3, 5, 7, 9, 11, 12, 13, 15 });

   numList.ForEach(i =>
   {
       if (i % 2 == 1)
           Console.Write(i);
       else
           return;
   });

   Console.ReadLine();
}

This will produce the output:

13579111315

Of course, what I'd really like it to do is to stop executing the ForEach function after 12, and not print 13 or 15. In a traditional foreach construct, you would have a break (instead of the return in my example), and the loop would end. However, a break is illegal in this case. You get the following message:

No enclosing loop out of which to break or continue

Is there a construct I could easily employ here to get the desired result, or is it just better to use a standard foreach loop in this case if you don't intend to actually run the desired code on every single member of a list?

like image 888
Nick Avatar asked Apr 28 '26 14:04

Nick


1 Answers

Just use a standard foreach loop. This is almost always simpler and less confusing than using a lambda expression - you don't get confusion over captured variables etc.

You may wish to read Eric Lippert's post on this as well.

List<T>.ForEach is useful if you've been handed a delegate and you just want to execute it on each element in the list - but otherwise I'd stick with the normal language feature.

like image 133
Jon Skeet Avatar answered Apr 30 '26 07:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!