Reputation: 142
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.
Upvotes: 0
Views: 15923
Reputation: 11
You could override the .ToString() method of your object and call that instead of creating a Display method. Then inside your loop you can do this:
foreach(Farm_Shop item in products.Values)
{
Console.WriteLine(item.ToString());
}
Upvotes: 0
Reputation: 711
It should read something like
foreach (var product in products)
{
product.Value.Display();
}
Now you can make your Display method more understandable this way:
public Display()
{
var out=String.Format("{1}\t{2}\t{3}\t{4}\t{5}",_id,_productName,_categoryName,_this,_that [...]);
Console.WriteLine(out);
}
Upvotes: 0
Reputation: 251
This will loop through each KeyValue pair in the dictionary and gets you the value for each jey
foreach (KeyValuePairtemp in products) //loop through the dictionary { Console.WriteLine(temp.Value); }
Upvotes: 0
Reputation: 56536
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();
}
Upvotes: 6