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?

Recommended Answers

All 3 Replies

Loops

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

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.

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());
    }   
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.