如何在C#中退出foreach循环? [英] How do I exit a foreach loop in C#?

查看:2854
本文介绍了如何在C#中退出foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 循环立即。我该怎么办?

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

推荐答案

使用 休息

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

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

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

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

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

这篇关于如何在C#中退出foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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