Restart a foreach loop in C#?

前端 未结 5 1221
傲寒
傲寒 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:23

    One way you can do that is using for, as you have already mentioned:

    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

    Action a;
    for(var index = 0; index < Constratins.Count; index++)
    {
       if(!Constraints[index].Allows(a))
       {
          a.Change();
          index = -1; // restart
       }
    }
    

提交回复
热议问题