0

嗨伙计们,您如何在 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
}

怎么做?

4

3 回答 3

9

虽然我不完全理解你的例子,但我想我理解你的问题。我遇到了同样的问题并且能够想出一个解决方案:在 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.
        }
     }
}

我知道我玩游戏已经很晚了,但希望这对在这里遇到同样问题的其他人有所帮助。

于 2016-03-30T20:08:43.333 回答
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")
}
于 2013-06-19T10:54:25.623 回答
2

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

for (int i = 0; i < inventoryTimeBlocks.Count; i++)
{
 if (line.Contains("a"))
     //next loop take "account1";
 else
 {
   if(i > 0)
   {
    i = i - 1;
    continue;
   }
 }
}
于 2017-06-06T09:39:40.437 回答