Search code examples
c#dictionaryforeachcollectionsgeneric-collections

Using foreach loop on Dictionary<>


When I was trying to use foreach loop with classes or a value type I was doing it like that

foreach(int item in items)
{
   //rest of the code
}

However when I tried to loop the Dictionary like that

foreach(Dictionary<TKey,TValue> item in dictionaryobject)
{
    //compile error
}

I got a compile error so I must use KeyValuePair<int, string>

foreach(KeyValuePair<int,string> item in dictionaryobject)
{
    //code
}

Why must I use KeyValuePair instead of the Dictionary?


Solution

  • Why must I use KeyValuePair instead of the Dictionary?

    Because KeyValuePair<TKey, TValue> is what the enumerator of GetEnumerator yields for each item in the dictionary. A Dictionary<TKey, TValue> implements IEnumerable(Of KeyValuePair(Of TKey, TValue)) and that interface needs to be implemented for foreach, so GetEnumerator is called when you use a foreach. See: Make a Visual C# class usable in a foreach statement

    If you have a List<int> each int is enumerated, but in case of a dictionary you want the pair of key and value.