Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart a foreach loop in C#?

Tags:

How can I restart a foreach loop in C#??

For example:

Action a; foreach(Constrain c in Constrains) {    if(!c.Allows(a))    {       a.Change();       restart;    } } 

restart here is like continue or break but it restarts the foreach from the begining It is like setting the counter of a for loop to 0 again..

Is that possible in C#?

Edit:I want to thank both Mehrdad Afshari and Mahesh Velaga for letting me discover a bug (index=0) in my current implementation, that would not have been discovered otherwise..

like image 928
Betamoo Avatar asked Jan 01 '11 12:01

Betamoo


1 Answers

Use the good old goto:

restart: foreach(Constrain c in Constrains) {    if(!c.Allows(a))    {       a.Change();       goto restart;    } } 

If you're diagnosed with gotophobia 100% of the time for some reason (which is not a good thing without a reason), you can try using a flag instead:

bool restart; do {    restart = false;    foreach(Constrain c in Constrains)    {       if(!c.Allows(a))       {          a.Change();          restart = true;          break;       }    } } while (restart); 
like image 170
mmx Avatar answered Sep 18 '22 14:09

mmx