C#根据foreach中的if语句转到列表中的下一项 [英] C# go to next item in list based on if statement in foreach

查看:28
本文介绍了C#根据foreach中的if语句转到列表中的下一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using C#. I have a list of items. I loop through each item using a foreach. Inside my foreach I have a lot of if statements checking some stuff. If any of these if statements returns a false then I want it to skip that item and go to the next item in the list. All if statements that follow should be ignored. I tried using a break but a break exits the whole foreach statement.

这是我目前拥有的:

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; 进入循环的下一次迭代,不再执行包含的代码.

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

官方文档在这里,但他们没有t 添加很多颜色.

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

这篇关于C#根据foreach中的if语句转到列表中的下一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆