2

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..

John Saunders
  • 160,644
  • 26
  • 247
  • 397
vbaid
  • 89
  • 1
  • 8
  • 3
    If you need keys too, don't iterate over `Values` :) Just iterate over the dictionary (each element is a key value pair), then within that, iterate over all of the values for that key. – crashmstr Jun 19 '15 at 19:28

3 Answers3

2

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
2

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.

1

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);
     }
}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112