Link to home
Start Free TrialLog in
Avatar of Camillia
CamilliaFlag for United States of America

asked on

2 Foreach loops

I have 2 rows of data like below and my code. I get the rows from database, I check for comma, and add to listbox. But what I'm doing below actually
add 5 rows and I think it's because of the 2 for each loops nested. I need 3 rows...not 5. Two of the rows get repeated...


     Bob Jones, Dave Jones      1, 11
        Jane Doe            12


I should get:
Bob Jones
Dave Jones
Jane Doe

But I get:

Bob Jones
Dave Jones
Bob Jones
Dave Jones
Jane Doe
foreach (var p in results)
                {
                    if (p.HCproviders.Contains(","))
                    {
                        String[] providerValues = p.HCproviders.Split(new Char[] { ',' });
                        String[] idValues = p.hcids.ToString().Split(new Char[] { ',' });
                        foreach (String i in providerValues)
                        {
                            foreach(string j in idValues)
 
                              lb.Items.Add(new ListItem(i, j));
                        } 
 

                    }
                    else
                    lb.Items.Add(new ListItem(p.HCproviders, p.hcids.ToString()));

                }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of disrupt
disrupt
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Use the following code instead:

foreach (var p in results)
                {
                    if (p.HCproviders.Contains(","))
                    {
                        String[] providerValues = p.HCproviders.Split(new Char[] { ',' });
                        String[] idValues = p.hcids.ToString().Split(new Char[] { ',' });
                        int index = 0;
                        foreach (String i in providerValues)
                        {
                            lb.Items.Add(new ListItem(i, idValues[j]));
                        }
 

                    }
                    else
                    lb.Items.Add(new ListItem(p.HCproviders, p.hcids.ToString()));

                }
Avatar of Camillia

ASKER

You have
 lb.Items.Add(new ListItem(i, idValues[j]));

What is j? did you mean "index"??