如何在c#上停止foreach循环

时间:2016-11-16 06:25:48

标签: c# xml

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

如何停止此循环?如果我想要val8="1"val1=="Abdullah" 在屏幕上显示我的数据,但这个循环进入无限循环 所以屏幕上没有显示任何内容。

3 个答案:

答案 0 :(得分:2)

以这种方式修正错误:

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

答案 1 :(得分:2)

或者您可以尝试使用“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
}

答案 2 :(得分:1)

您可以使用goto声明:

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

标签Finished应放在最外面foreachXElement element2 in doc.Descendants("sif"))的右括号后面。你的工作就像以下一样:

Finished: 
    ;

您可以在dot-net-fiddle处查看此内容。