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

Whenever violated is true, I want to get out of the foreach loop immediately. How do I do it?

4

5 回答 5

227

Use break.


Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);
于 2009-01-19T01:11:13.703 回答
133

Just use the statement:

break;
于 2009-01-19T01:12:08.287 回答
39

Use the break keyword.

于 2009-01-19T01:12:04.870 回答
16

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

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;
   }
}
于 2016-06-06T23:10:49.830 回答
0

在测试期间,我发现 break 后的 foreach 循环进入循环而不是循环之外。因此,我将 foreach 更改为 for ,并且在这种情况下 break 可以正常工作-在 break 程序流退出循环后。

于 2017-06-22T09:48:36.720 回答