在C#中退出foreach循环

74 c#

foreach (var name in parent.names)
{
    if name.lastname == null)
    {
        Violated = true;
        this.message = "lastname reqd";
    }

    if (!Violated)
    {
        Violated = !(name.firstname == null) ? false : true;
        if (ruleViolated)
            this.message = "firstname reqd";
    }
}
Run Code Online (Sandbox Code Playgroud)

只要违反是真的,我想foreach立即退出循环.我该怎么做?

con*_*tor 191

使用 break;


编辑:

与您的问题无关,我在您的代码中看到以下行:

Violated = !(name.firstname == null) ? false : true;
Run Code Online (Sandbox Code Playgroud)

在这一行中,您将获取一个布尔值(name.firstname == null).然后,您将!运算符应用于它.然后,如果值为true,则将Violated设置为false; 否则为真.所以基本上,Violated设置为与原始表达式相同的值(name.firstname == null).为什么不使用它,如:

Violated = (name.firstname == null);
Run Code Online (Sandbox Code Playgroud)

  • +1用于纠正他没有询问的错误. (22认同)
  • @DovMiller解释不适合评论框,另外我也得到了实际问题的答案. (6认同)
  • 我不喜欢看到不必要的 if 测试和否定。 (2认同)

Sam*_*uel 26

使用break关键字.


小智 11

break;- 退出foreach

continue;- 跳转到下一个值


小智 7

看看这段代码,它可以帮助你快速走出循环!

foreach (var name in parent.names)
{
   if (name.lastname == null)
   {
      Violated = true;
      this.message = "lastname reqd";
      break;
   }
   else if (name.firstname == null)
   {
      Violated = true;
      this.message = "firstname reqd";
      break;
   }
}
Run Code Online (Sandbox Code Playgroud)