简体   繁体   English

如何在C#上停止foreach循环

[英]How to stop foreach loop on c#

XDocument doc = XDocument.Load(@"XMLFile1.xml");
Kullanıcılar _kullanici = new Kullanıcılar();
string password = pnb2.Password; 
foreach (XElement element2 in doc.Descendants("sif"))
{
    foreach (XElement element1 in doc.Descendants("iban"))
    {
        foreach (XElement element3 in doc.Descendants("accountno"))
        {
            foreach (XElement element4 in doc.Descendants("money"))
            {               
                foreach (XElement element8 in doc.Descendants("acc"))
                {
                    string val1 = element2.Value;
                    string val2 = element1.Value;
                    string val3 = element3.Value;
                    string val4 = element4.Value;
                    string val8 = element8.Value;
                    if (val8 == "1" && val1 == "Abdullah")
                    {                                               
                        lbl1.Content = ("İban Numaranız :" + val2);
                        lbl2.Content = ("Hesap Numaranız :" + val3);
                        lbl3.Content = ("Bakiyeniz :" + val4);
                    }
                }  
            }
        }
    }
}

How can I stop this loop ? 如何停止此循环? If val8="1" and val1=="Abdullah" I would like to show my data on the screen but this loop is entering an endless loop so nothing shows on the screen. 如果val8="1"val1=="Abdullah"我想在屏幕上显示我的数据,但是此循环进入了一个无穷循环,因此屏幕上没有任何显示。

Fixed error in this way: 通过这种方式修复错误:

if (val8 == "1" && val1 == "Abdullah")
{
    lbl1.Content = ("Iban Numaraniz :" + val2);
    lbl2.Content = ("Hesap Numaraniz :" + val3);
    lbl3.Content = ("Bakiyeniz :" + val4);
    return;
}  

or you could try using "break" to stop the loop. 或者您可以尝试使用“ break”来停止循环。

if (val8 == "1" && val1 == "Abdullah")
{                                               
     lbl1.Content = ("İban Numaranız :" + val2);
     lbl2.Content = ("Hesap Numaranız :" + val3);
     lbl3.Content = ("Bakiyeniz :" + val4);
     break; //stops the loop
}

You could make use of a goto statement: 您可以使用goto语句:

if (val8 == "1" && val1 == "Abdullah")
{
    lbl1.Content = ("İban Numaranız :" + val2);
    lbl2.Content = ("Hesap Numaranız :" + val3);
    lbl3.Content = ("Bakiyeniz :" + val4);
    goto Finished;
}  

The label Finished should be placed after the closing bracket of the outer most foreach ( XElement element2 in doc.Descendants("sif") ). 标签Finished应该放在最外面的foreach XElement element2 in doc.Descendants("sif") )。 Something like the following does your job: 类似于以下内容的工作:

Finished: 
    ;

You could check this at dot-net-fiddle . 您可以在dot-net-fiddle上进行检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM