我正在使用 C#。我有一个项目 list 。我使用 foreach
遍历每个项目。在我的 foreach
中,我有很多 if
语句检查一些东西。如果这些 if
语句中的任何一个返回 false,那么我希望它跳过该项目并转到列表中的下一个项目。应忽略后面的所有 if
语句。我尝试使用中断,但中断会退出整个 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
}
}
谢谢
最佳答案
使用 continue;
而不是 break;
进入循环的下一次迭代而不执行任何更多包含的代码。
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;
}
}
官方文档是here , 但它们不会添加太多颜色。
关于C#根据foreach中的if语句转到列表中的下一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4266456/