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

91

我正在使用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
   }
}

谢谢

6个回答

181

使用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;
   }
}

官方文档在这里,但它们没有添加太多的色彩。


1
谢谢。我以为continue是在foreach的主体中继续执行。 - Brendan Vogt
@Brendan - 要做到这一点,您只需不使用任何控制语句,就像它是循环外的if语句级联一样。 - Steve Townsend
对于在使用 VB 的其他查看者,语法是 [code] Continue For [/code]。 - Onthrax

23

试一下这个:

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

23

你应该使用:

continue;

9
continue 关键字可以实现你想要的功能。避免使用 break 关键字,因为它会退出 foreach 循环。

7
请使用continue代替break。 :-)

1

continue; 会按照你的预期跳到 foreach 循环中的下一项。

continue; 会跳过当前项,继续执行 foreach 循环中的下一项。

break; 会跳出循环,并在 foreach 循环结束后继续执行代码。


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接