开发者

Emulate break statement in ForEach function

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:

st开发者_运维百科atic 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜