im useless
im useless

Reputation: 7451

Stop Looping C#?

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));
}

Upvotes: 31

Views: 75134

Answers (6)

Ajith
Ajith

Reputation: 1535

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;

Upvotes: 5

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

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.

Upvotes: 16

cordellcp3
cordellcp3

Reputation: 3623

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
}   

Upvotes: 2

Rafal Spacjer
Rafal Spacjer

Reputation: 4918

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;
 }
}

Upvotes: 8

Anuraj
Anuraj

Reputation: 19598

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

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

Upvotes: 2

Paweł Smejda
Paweł Smejda

Reputation: 2005

you can skip iteration with

continue; 

and stop loop with

break;

Upvotes: 58

Related Questions