27

How to stop my Loop if the value is already existing?

here's my code in C#...

foreach (ArrayList item in ArrData)
{    
  HCSProvider.NewProviderResult oResult;
  oResult = oHCSProvider.CreateNewProvider(providercode, oProviderDetail)

  DBInterface ProviderDetail = new DBInterface(); 

  ProviderDetail.InsertProvider(Convert.ToInt64(providercode), Convert.ToString(oProviderDetail));
}
2

6 Answers 6

53

you can skip iteration with

continue; 

and stop loop with

break;
1
  • if there is an existing values in my database or after inserting a values my loop will stop?
    – im useless
    Mar 30, 2011 at 5:57
16

If you are inside a loop and want to abort the loop execution and jump to the code after the loop, insert a break; statement.

If you only want to stop the current loop iteration, and continue with the rest of the loop, add a continue; statement instead.

8

You can stop any loop in c# by a break statement

You can write something like this:

foreach(var o in list)
{
 if (o.SomeValue == 1)
 {
   break;
 }
}
4

Continue, break and goto are used in C# for skipping the loop.

Continue Skips the execution of current iteration

Continue;

break Comes out of the loop and continues the next statement after the loop

break;

goto is normally not recommend, but still can be used to move control out of the loop

goto Outer;
2

You can put a break command to exit from For Loop.

foreach(var item in items)
{
if(item == myitem)
{
break;
}
Console.WriteLine(item);
}
2

you can easily stop your lop on a condition with the break statement!

Small example:

var arr = new [] {1,2,3,4,5,6,7};
int temp = 0;

foreach(var item in arr)
{
    temp = item +1;
    if(temp == 5)
    {
        break;
            //...
    }
     //do something
}   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.