0

Hi, ive been trying to print out a dictionary item with its List but im so confused about it.

Basically I created a dictionary and I managed to add an Item to the dictionary(as a Key) and List of something (as value)

    Dictionary<String, List<string>> dic = new Dictionary<String, List<string>>();

    public void addItem(Item newItem)
         {
             List<string> info = new List<string>();
             dic.Add(newItem.getItemName(), info);
             info.Add(newItem.getDescription());
             info.Add(newItem.getManufacturer());
         }

Im confused how am I going to print an Item in the dictionary with its description and manufacturer like if im going to add a code

public void listItemInfo(String itemName)
    {

    }

any ideas?

4
Contributors
3
Replies
22
Views
4 Years
Discussion Span
Last Post by tinstaafl
0

Loops

foreach(String key in dic.Keys) {
    foreach(String item in dic[key]) {
        Console.Write("{0}, ", item);
    }
    Console.WriteLine();
}
0

dic[key] will give you your List<String> back.

However, I would question why you're adding the strings to this dictionary, rather than creating a list of items. Additionally, the way you're currently doing it, you have no idea of knowing which string corresponds to the manufacturer or the description.

Edited by Ketsuekiame

0

if newItem is the structure your passing you could make your dictionary of that type, then add newItem directly to the dictionary. something like this might work:

    Dictionary<String, Item> dic = new Dictionary<String, Item>();

    public void addItem(Item newItem)
    {
        dic.Add(newItem.getItemName(), newItem);
    }
    public void listItemInfo(String itemName)
    {
            Console.Write("Name: {0}\n", dic[itemName].getItemName());
            Console.Write("Description: {0}\n", dic[itemName].getDescription());
            Console.Write("Manufacturer: {0}\n\n", dic[itemName].getManufacturer());
    }   

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.