Meghan Gibbs
Meghan Gibbs

Reputation: 15

for statement inside a for each in c#

What is wrong? Basically want to extract each code in each row of table "Service" And if it is equal to specific text then set each corresponding row with matching text.

foreach (DataRow code in dsAuthors.Tables["Service"].Rows)
{

   for (int i = 0; i < dsAuthors.Tables[1].Rows.Count; i++)
    {

        if (code[1].ToString() == "01")
        {
            Shipment.Rows[i][0] = "Service 1";
        }
        else if (code[1].ToString() == "02")
        {
            Shipment.Rows[i][0] = "Service 2";
        }
        else if (code[1].ToString() == "03")
        {
            Shipment.Rows[i][0] = "Service 3";
        }
    }
}

It just fills all rows in with Service 1 but i don't want it to.

Sorry was NOT meant to have both tables be the same i have updated the code to be more accurate i believe.

Upvotes: 0

Views: 459

Answers (2)

David Yaw
David Yaw

Reputation: 27864

You're iterating over the list of rows twice. You're reading data from the variable from the outer loop, and writing to the index from the inner loop. It's writing "Service 1" to all rows because the last row is "01", and the inner loop writes that to all rows.

Try this instead:

var Service = dsAuthors.Tables["Service"];
for (int i = 0; i < Service.Rows.Count; i++)
{
    if (Service.Rows[i][1].ToString() == "01")
    {
        Shipment.Rows[i][0] = "Service 1";
    }
    else if (Service.Rows[i][1].ToString() == "02")
    {
        Shipment.Rows[i][0] = "Service 2";
    }
}

Upvotes: 2

Jeff Watkins
Jeff Watkins

Reputation: 6359

You're looping on the same thing twice, then poking a value into shipment rows unbounded. It doesn't look very safe and given you're looping and setting the shipment rows through the entire collection inside the foreach, it means the last value will determine the content of ALL shipment rows.

Check it out in a debugger, you'll see that when you hit a Service 2 value, all shipment rows will be set to 2 in the loop etc.

Upvotes: 3

Related Questions