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

问题描述 投票:0回答:6

我正在使用 C#。我有一份物品清单。我使用

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
   }
}
c# asp.net if-statement
6个回答
182
投票

使用

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,但它们并没有添加太多色彩。


23
投票

试试这个:

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

23
投票

您应该使用:

continue;

9
投票

continue
关键字将满足您的需求。
break
将退出
foreach
循环,因此您需要避免这种情况。


7
投票

使用

continue
而不是
break
。 :-)


1
投票

继续;将按照您期望的休息方式工作;在这里工作。

继续;将跳到 foreach 循环中的下一项

打破;将跳出循环并继续执行 foreach 循环结束处的代码。

© www.soinside.com 2019 - 2024. All rights reserved.