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?
3
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.
Regarding:
foreach(int item in items)
Assuming items
is e.g. a List<int>
(or similar), it makes sense to use int item
in a for-each loop, because each entry in the collection is an int
.
But in this line:
foreach(Dictionary<TKey,TValue> item in dictionaryobject)
Assuming dictionaryobject
is a Dictionary
, each element is not a Dictionary<TKey,TValue>
.
Therefore the 2 lines are not correlated.
The correlative version is indeed:
foreach(KeyValuePair<int,string> item in dictionaryobject)
Because each element in a Dictionary
is a KeyValuePair<int,string>
.
2
Your dictionary is dictionaryobject
. when iterating over it, each iteration provides a pair of key and value, not another dictionary – hence, the KeyValuePair<int,string>
.