如何在C#中退出foreach循环?


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

每当违反为真时,我都想foreach立即退出循环。我该怎么做?

Answers:


208

使用break


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

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

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

Violated = (name.firstname == null);

我不希望看到不必要的测试和否定。
John Grabauskas,



9

看这段代码,它可以帮助您快速摆脱循环!

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.