foreach with Generic Dictionary
Posted by Vadim on March 30, 2008
I decided to write this post because few people approached me with the question: “Is there a way to use foreach iteration statement with Dictionary<TKey, TValue> object?”
The quick response is: “Yes, use KeyValuePair.”
However, it wasn’t enough and I had to show an example.
Before I will show an example here, I want to remind you that Dictionary<TKey, TValue> class implements IDictionary<TKey, TValue> interface that extends ICollection<KeyValuePair<TKey, TValue> which in it turn is derived from IEnumerable<KeyValuePair<TKey, TValue>. As we know every class that implements IEnumerable interface must implement the GetEnumerator method. And that is the reason why we can use foreach iteration statement.
Here’s the promised example.