如何在foreach中重复一个循环

时间:2013-06-19 10:51:38

标签: c# for-loop

大家好,你怎么能在foreach中重复一次迭代?

foreach (string line in File.ReadLines("file.txt"))
{
     // now line == "account", next line == "account1"
     if (line.Contains("a"))
         //next loop take "account1";
     else
        // need to set that next loop will take line == "account" again
}

怎么做?

3 个答案:

答案 0 :(得分:4)

没有必要更改代码,假设它在循环中只有if/else构造。

if条件评估为true时,else将不会执行并且循环恢复。

在一个更复杂的地方,您希望立即恢复循环并确保在条件执行后没有其他任何内容,请使用continue语句:

  

continue语句将控制权传递给封闭的while,do,for或foreach语句的下一次迭代。

foreach (string line in File.ReadLines("file.txt"))
{
     // now line == "account", next line == "account1"
     if (line.Contains("a"))
         continue;
     else
        // need to set that next loop will take line == "account" again

     // more stuff that we don't want to execute if line.Contains("a")
}

答案 1 :(得分:4)

虽然我不完全理解你的例子,但我想我理解你的问题。我有同样的问题,并能够提出一个解决方案:在foreach中包含一个while循环。在您的示例中,它看起来像这样:

foreach (string line in File.ReadLines("file.txt"))
{
    bool repeat = true;
    while (repeat)
    {
        // now line == "account", next line == "account1"
        if (line.Contains("a"))
        {
            //do your logic for a break-out case
            repeat = false;
        }
        else 
        {
          //do your logic for a repeat case on the same foreach element
          //in this instance you'll need to add an "a" to the line at some point, to avoid an infinite loop.
        }
     }
}

我知道我在游戏中已经很晚了,但希望这对于那些在这里遇到同样问题的人来说会有所帮助。

答案 2 :(得分:1)

我想如果其他人来这也可能会有帮助

for (int i = 0; i < inventoryTimeBlocks.Count; i++)
{
 if (line.Contains("a"))
     //next loop take "account1";
 else
 {
   if(i > 0)
   {
    i = i - 1;
    continue;
   }
 }
}