Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: (untagged)
Hello Everyone,

This is my first time dealing with an array list along side a loop. I am thought that I understood it pretty well. So I started to make a simple Grocery List program. However, I cannot seem to get the foreach to allow me to use the item variable. Any pointers would be greatly appreciated. Thanks in advance!

C#
namespace VS_Console_Sand_Box
{
    class Program
    {
        static void Main(string[] args)
        {
            string item;

            List<string> GroceryList = new List<string>();

            do
            {
                Console.WriteLine("Enter new grocery item");
                Console.WriteLine("Enter Q to quit");
                item = Convert.ToString(Console.ReadLine());

                if (item == "Q")
                {
                    foreach (string item in GroceryList)
                    {
                        Console.WriteLine(GroceryList);
                    }
                    break;
                }
                else
                {
                    GroceryList.Add(item);
                }
            }
            while (item != "Q");
            Console.ReadLine();
        }
    }
}
Posted
Comments
[no name] 7-Oct-14 17:28pm    
Console.WriteLine(item);

1 solution

in

C#
foreach (string item in GroceryList)
                    {
                        Console.WriteLine(GroceryList);
                    }
                    break;


wouldn't you be better off doing

C#
Console.WriteLine(item);


Also note that 'item' here has completely different 'scope' to the item declared at the top of your program - in fact, I prefer not to do this as all - I make the variable name in the foreach reflective of the list - so I might use

C#
foreach (string GroceryListitem in GroceryList)
                    {
                        Console.WriteLine(GroceryListitem);
                    }
                    break;



is that what you were looking for ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900