C # 根据 foreach 中的 if 语句转到 list 中的下一项

我用的是 C # 。我有一份物品清单。我使用 foreach循环遍历每个项目。在我的 foreach中,我有很多 if语句检查一些东西。如果这些 if语句中的任何一个返回 false,那么我希望它跳过该项,转到列表中的下一项。后面的所有 if语句都应该被忽略。我尝试使用 break,但 break 退出了整个 foreach语句。

这是我目前拥有的:

foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list.  Skip/ignore all validation
// that follows beneath
}


if (item.Weight > 100)
{
// Display error message and move to next item in list.  Skip/ignore all validation
// that follows beneath
}
}

谢谢

143130 次浏览

Try this:

foreach (Item item in myItemsList)
{
if (SkipCondition) continue;
// More stuff here
}

Use continue; instead of break; to enter the next iteration of the loop without executing any more of the contained code.

foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list.  Skip/ignore all validation
// that follows beneath
continue;
}


if (item.Weight > 100)
{
// Display error message and move to next item in list.  Skip/ignore all validation
// that follows beneath
continue;
}
}

Official docs are here, but they don't add very much color.

Use continue instead of break. :-)

The continue keyword will do what you are after. break will exit out of the foreach loop, so you'll want to avoid that.

You should use:

continue;

continue; will work how you are expecting break; to work here.

continue; will skip to the next item in the foreach loop

break; will break out of the loop and continue the code where thr foreach loop ends.