David Gebbett
David Gebbett

Reputation: 45

Why is my for loop skipping to the end?

I have been asked to create a mini and basic shopping basket, the code was working but recently the for loops that i have created to search through an array are skipping all the code inside the loop. I have provided the code below:

for (int i = 0; i < OrderItems.Count; i++)
    {
        //if a match is found it will add to the to the current quantity
        if (OrderItems[i].ProductName == productName)
            OrderItems[i].AddItem(latestValue, quantity);

         //If no match was found in the list it will get added
        else
            OrderItems.Add(new OrderItem(productName, latestValue, quantity));
    }

I am new fairly new c# and i may have missed something silly Thanks for any help that can be provided

Upvotes: 0

Views: 259

Answers (3)

Haney
Haney

Reputation: 34762

This means your OrderItems is empty, and the Count property is returning 0, so the loop doesn't execute. You must have OrderItems if you want your loop to execute.

Upvotes: 0

JustCode
JustCode

Reputation: 312

Please check the count for OrderItems in debugger or print it. Is it zero due to someother error occured before this function / code execution.

Upvotes: 0

Fun Mun Pieng
Fun Mun Pieng

Reputation: 6891

I think your code should look like this:

bool found = false;
for (int i = 0; i < OrderItems.Count; i++)
{
    //if a match is found it will add to the to the current quantity
    if (OrderItems[i].ProductName == productName) {
        OrderItems[i].AddItem(latestValue, quantity);
        found = true;
    }
}

//If no match was found in the list it will get added
if (! found)
    OrderItems.Add(new OrderItem(productName, latestValue, quantity));

You will need to loop through existing item. If found, update that item. After you have checked all the items, only then do you check whether you have found the item. If you have not found the item, add that as a new item.

Your original code did not work because there was no item in OrderItems, and the else statement will never be executed.

And you might want to consider renaming the method to UpdateItem instead of AddItem if the method actually updates the item.

Upvotes: 3

Related Questions