C#去下一个项目名单的基础上,如果在foreach语句 [英] C# go to next item in list based on if statement in foreach

查看:148
本文介绍了C#去下一个项目名单的基础上,如果在foreach语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#。我有一个项目清单。通过每一个项目我循环使用的foreach 。里面我的foreach 如果语句检查一些东西,我有很多的的。如果这些如果语句返回false,那么我想它跳过该项目并进入下一个项目在列表中。随后所有的如果的声明应被忽略。我试图用一个突破,但突破退出整个的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
   }
}

感谢

推荐答案

使用继续; 而不是打破; 进入循环的下一次迭代,而不执行包含$ C $中任意更

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.

这篇关于C#去下一个项目名单的基础上,如果在foreach语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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