A.Gecu
A.Gecu

Reputation: 93

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.

Upvotes: 2

Views: 3846

Answers (3)

Sonny Recio
Sonny Recio

Reputation: 109

or you could try using "break" to stop the loop.

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
}

Upvotes: 2

A.Gecu
A.Gecu

Reputation: 93

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

Upvotes: 2

Christos
Christos

Reputation: 53958

You could make use of a goto statement:

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")). Something like the following does your job:

Finished: 
    ;

You could check this at dot-net-fiddle.

Upvotes: 1

Related Questions