Restart a foreach loop in C#?

前端 未结 5 1276
傲寒
傲寒 2021-02-07 04:02

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

For example:

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


        
5条回答
  •  轮回少年
    2021-02-07 04:10

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

提交回复
热议问题