How TO Exit a foreach early

  • Thread starter Thread starter Tom
  • Start date Start date
T

Tom

I know how to construct a foreach.

I need to know if a condition is met, how do I exit the
foreach early so as avaoid the roundtrips for the loop.

Thanks

Tom
 
Tom said:
I know how to construct a foreach.

I need to know if a condition is met, how do I exit the
foreach early so as avaoid the roundtrips for the loop.

You can use break and continue in foreach just as you can in for:

using System;

public class Test
{
static void Main()
{
string[] foo = new string[] {"first", "second", "third"};

foreach (string x in foo)
{
Console.WriteLine(x);
if (x=="second")
{
Console.WriteLine ("Exiting loop");
break;
}
}
}
}
 
Gawelek said:
Maybe "while" will be better ?

Why? You've then got to do the iteration separately. I can see that in
some cases that would provide clearer code, but I don't think it would
most of the time. Then again, I know there's considerable debate about
the pros and cons of break, continue, and having multiple return points
in a method.
 
Back
Top