C#-foreach循环在while循环中-跳出foreach并立即继续while循环
本文关键字:循环 while foreach 继续 C#-foreach 跳出 | 更新日期: 2023-09-27 18:02:07
while (foo() == true)
{
foreach (var x in xs)
{
if (bar(x) == true)
{
//"break;" out of this foreach
//AND "continue;" on the while loop.
}
}
//If I didn't continue, do other stuff.
}
我有点纠结于怎么做。
更新:我解决了这个问题。我忽略了这样一个事实:如果我不在while循环中调用continue;
,我需要处理其他东西。
对不起,我没有意识到我用了两次"某物"这个词。
我会重写这个:
while (foo() == true)
{
foreach (var x in xs)
{
if (bar(x) == true)
{
//"break;" out of this foreach
//AND "continue;" on the while loop.
}
}
//If I didn't continue, do other stuff.
DoStuff();
}
作为
while (foo()) // eliminate redundant comparison to "true".
{
// Eliminate unnecessary loop; the loop is just
// for checking to see if any member of xs matches predicate bar, so
// just see if any member of xs matches predicate bar!
if (!xs.Any(bar))
{
DoStuff();
}
}
while (something)
{
foreach (var x in xs)
{
if (something is true)
{
//Break out of this foreach
//AND "continue;" on the while loop.
break;
}
}
}
如果我理解正确,您可以在这里使用LINQ Any/All谓词:
while (something)
{
// You can also write this with the Enumerable.All method
if(!xs.Any(x => somePredicate(x))
{
// Place code meant for the "If I didn't continue, do other stuff."
// block here.
}
}
这应该能满足您的需求:
while (something)
{
bool doContinue = false;
foreach (var x in xs)
{
if (something is true)
{
//Break out of this foreach
//AND "continue;" on the while loop.
doContinue = true;
break;
}
}
if (doContinue)
continue;
// Additional items.
}
只要您需要break
通过嵌套结构进行传播,这种代码就会频繁出现。这是否是一种代码气味还有待商榷:-(
while (something)
{
foreach (var x in xs)
{
if (something is true)
{
break;
}
}
}
然而,这两个值难道不总是等于真的吗???
所以你想在中断后继续吗?
while (something)
{
bool hit = false;
foreach (var x in xs)
{
if (something is true)
{
hit = true;
break;
}
}
if(hit)
continue;
}