tags:

views:

126

answers:

1

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?

+3  A: 

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.

Jon Skeet
Thanks for the link. I had a feeling this was the answer, but was curious what others thought. Sometimes its as if Lambdas are really over used over more "traditional" sequences.
Nick
@Nick: Yes, I know what you mean. There is a temptation to use them everywhere...
Jon Skeet
Interestingly, this is also an issue when using .NET parallel foreach constructs, which use delegates in much the same way. Their solution was to add a LoopState mechanism. You can see an example here: http://msdn.microsoft.com/en-us/library/dd460721%28VS.100%29.aspx
LBushkin
@LBushkin - Thanks for the added info... I hadn't thought of the parallel extensions when I wrote my question, but the same problem would definitely apply.
Nick