m-y*_*m-y 6 c# for-loop continue break while-loop
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.
}
Run Code Online (Sandbox Code Playgroud)
我有点坚持如何做到这一点.
更新:我修正了问题.我遗漏了一个事实,即如果我不在continue;while循环上调用,我需要处理其他内容.
对不起,我没有意识到我曾两次使用"某事"这个词.
Eri*_*ert 14
我会改写这个:
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();
}
Run Code Online (Sandbox Code Playgroud)
如
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();
}
}
Run Code Online (Sandbox Code Playgroud)
while (something)
{
foreach (var x in xs)
{
if (something is true)
{
//Break out of this foreach
//AND "continue;" on the while loop.
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,您可以在此处使用 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.
}
}
Run Code Online (Sandbox Code Playgroud)