如何重置或重新启动嵌套循环

时间:2010-12-06 22:30:36

标签: c# loops nested

loop one
{
    looptwo
    {
        if(condition=true)
        {
           reset values//restart both loops
        }
     }
}
and possibilities for reset values is 3

basically i want to compair two matrices

a= 1 2 3 4

   1 2 3 4 
b= 3 4 5 6
   4 6 7 8

and when row 1 of a[] is matched with row 1 of b[].....i will add these rows and a[]
become = 2 4 6 8

for(i=0;i<rows;i++)
for(j=0;j<columns;j++)
{
a[i]=a[i]+b[i,j] 
}

再次使用新的[] Matrix

重新启动我的maches

我必须确保用[]检查b []矩阵的所有行,在这种情况下为3

5 个答案:

答案 0 :(得分:2)

你必须使用goto来打破C#中的多个循环级别。例如:

RESTART:
    while (a) {
        while (b) {
            if (that_other_thing)
                goto RESTART;
        }
    }

好吧,你没有使用goto,但替代方法可能是使用一堆标志变量来表示需要重启。而且这些代码可能很难遵循。

答案 1 :(得分:1)

这里最好的选择是将循环移动到它们自己的方法中,并从内循环内部返回。例如:

public void MyMehod(){
  loop one{
    looptwo{
      if(condition=true){
        return;
      }
    }
  }
}

如果由于某种原因这是不可能的,你可以使用你在内部循环中设置的bool值来摆脱所有这些,但这有点麻烦:

bool endloop = false;
while(!endloop){
  while(!endloop){
    if(condition){
      endloop = true;
    }
  }
}

对于while循环,它看起来没问题,但对for循环或foreach循环来说更麻烦。

答案 2 :(得分:0)

            Start:
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    if(j == 5)
                        goto Start;
                }
            }

尽管以不使用goto的方式构建代码是一种更好的方法......

答案 3 :(得分:0)

如果您可以保证您的条件会告诉您不需要重新启动,那么您可以将整个事情包裹起来。

bool keepLooping = true;
while (keepLooping)
{
  keepLooping = false;
  for (int x = 0; x < maxx; x++)
  {
    for (int y = 0; y < maxy; y++)
    {
      if (DoSomething(x, y))
      {
        keepLooping = true;
        break;
      }
    }
    if (keepLooping)
    {
      break;
    }
  }
}

如果要检查重复列表并修改它们确实使所有条目都是唯一的,那么您可以执行以下操作(假设字符串值):

List<string> a = GetNamesFromeSomewhere();

bool duplicateFound = true;
while (duplicateFound )
{
  duplicateFound = false;
  for (int x = 0; x < a.Length; x++)
  {
    for (int y = x + 1; y < a.Length; y++)
    {
      if (a[x].Equals(a[y]))
      {
        //Change a[y], but now we have to recheck for duplicates...
        a[y] += "_";
        duplicateFound = true;
        break;
      }
    }
    if (duplicateFound)
    {
      break;
    }
  }
}

答案 4 :(得分:0)

如果你使用像i和j这样的数字循环变量,你可以重置值

e.g。

for (i=0; i<10; i++) {
   for (j=0; j<10; j++) {
      if (var[i][j] == 'x') {
         i=0; j=0; break;
      }
   }
}

您也可以使用前面建议的方法

void someFunction(params) {
   for (i=0; i<10; i++) {
      for (j=0; j<10; j++) {
         if (var[i][j] == 'x') {
            someFunction(params)
            return;
         }
      }
   }       
}