在C#退出foreach循环 [英] Exiting foreach loop in C#

查看:201
本文介绍了在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 == NULL)。然后,您应用运营商给它。然后,如果该值为true,您可以设置侵犯了虚假的;否则为true。所以基本上,触犯被设置为相同的值作为原始表达式(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天全站免登陆