Search code examples
c#arrayscollectionsdictionarygeneric-collections

How do I print a Dictionary collection in C#?


I'm attempting to print out an array/collection here. I have a class file with the following code to print out the text:

//Display All
    public void Display()
    {
        Console.WriteLine(ID + "\t" + Product + "\t" + Category + "\t" + Price + "\t" + Stock + "\t" + InBasket);
    }

Then, in main I attempt to actually print it out onto screen using this:

foreach (KeyValuePair<int, Farm_Shop> temp in products)
        {
            //display each product to console by using Display method in Farm Shop class
            temp.Display();
        }

However I get the following error:

'System.Collections.Generic.KeyValuePair<int,Farm_Shop_Assignment.Farm_Shop>' 
does not contain a definition for 'Display' and no extension method 'Display'
accepting a first argument of type 
'System.Collections.Generic.KeyValuePair<int,Farm_Shop_Assignment.Farm_Shop>' 
could be found (are you missing a using directive or an assembly reference?)

Here is the actual content I want to print out:

products = new Dictionary<int, Farm_Shop>
        {
            { 1, new Farm_Shop(1, "Apple", "Fruit\t", 0.49, 40, 'n') },
            { 2, new Farm_Shop(2, "Orange", "Fruit\t", 0.59, 35, 'n') }
        };

From my understanding, this isn't working as I am only sending an array/collection to be printed, and not the int which is meant to come before it, if you know what I mean.

Can someone tell me how I would go about getting it to print correctly.

Much appreciated. Thanks.


Solution

  • Display() is a method on Farm_Shop. You can't call it directly on an object of type KeyValuePair<int, Farm_Shop>. You should do this to access the Farm_Shop instance in your key/value pair:

    foreach (KeyValuePair<int, Farm_Shop> temp in products)
        {
            //display each product to console by using Display method in Farm Shop class
            temp.Value.Display();
        }
    

    Or loop through the Values property, since the key doesn't add much for you (since it came from a property on Farm_Shop:

    foreach (Farm_Shop temp in products.Values)
        {
            //display each product to console by using Display method in Farm Shop class
            temp.Display();
        }