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?