How to get Key, Value from dictionary when value is a list

1.3k views Asked by At

so basically I have a dictionary where I have a key, and then the value is a list that contains strings.. so for example..

{"key1", list1}
list1 = [Value 1 Value2, Value3]

And I have multiple keys and therefore values that have lists. I want to display it so that it shows

Key1: Value1
Key1: Value2
Key1: Value3

So I want to be able to display the Key and also the value. But I am unsure of how to do that.

foreach (var value in FoodCategory_Item.Values)
{
    foreach(var item in value)
    {
        Console.WriteLine("Value of the Dictionary Item is: {0}", item);
    }
}

That's what I have so far, which is to iterate over the values, which I know how to do, but I am not sure how to get the key values in there as well, because it will iterate over all the values first, and then iterate through the key items..

3

There are 3 answers

1
Andrew Whitaker On

This should work:

foreach (KeyValuePair<string, List<string>> kvp in FoodCategory_Item)
{
    foreach (string item in kvp.Value)
    {
        Console.WriteLine ("{0}: {1}", kvp.Key, item);
    }
}

Dictionary implements IEnumerable<KeyValuePair<TKey, TValue>>, so you can iterate over it directly.

0
Jonesopolis On

Dictionary is enumerable, so iterate that:

foreach (var kvp in FoodCategory_Item)
{
     foreach(var item in kvp.Value)
     {
         Console.WriteLine("Value of the Dictionary Key {0} is: {1}", kvp.Key ,item);
     }
}
0
AudioBubble On

If you look at the documentation for Dictionary, you will notice that it implements the interface

IEnumerable<KeyValuePair<TKey, TValue>>

Hence, you can do the following:

foreach(KeyValuePair<TKeyType, TValueType> kvp in dictionary)
{
    foreach(var item in kvp.Value)
    {
        Console.WriteLine("{0}: {1}", kvp.Key, item);
    }
}

In the example code given here, replace TKeyType with the actual type of the keys used in your dictionary, and replace TValueType with the list type used for the the values of the dictionary.