4.10. Using foreach with Generic Dictionary Types
Problem
You need to enumerate the elements within a type that implements System.Collections.Generic.IDictionary, such as System.Collections.Generic.Dictionary or System.Collections.Generic.SortedList.
Solution
The simplest way is to use the KeyValuePair structure in a foreach loop, as shown here:
// Create a Dictionary object and populate it
Dictionary<int, string> myStringDict = new Dictionary<int, string>()
{ { 1, "Foo" }, { 2, "Bar" }, { 3, "Baz" } };
// Enumerate and display all key and value pairs.
foreach (KeyValuePair<int, string> kvp in myStringDict)
{
Console.WriteLine("key " + kvp.Key);
Console.WriteLine("Value " + kvp.Value);
}Discussion
The nongeneric System.Collections.Hashtable (the counterpart to the System.Collections.Generic.Dictionary class), System.Collections.CollectionBase, and System.Collections.SortedList classes support foreach using the DictionaryEntry type, as shown here:
Hashtable myHashtable = new Hashtable()
{ { 1, "Foo" }, { 2, "Bar" }, { 3, "Baz" } };
foreach (DictionaryEntry de in myHashtable)
{
Console.WriteLine("key " + de.Key);
Console.WriteLine("Value " + de.Value);
Console.WriteLine("kvp " + de.ToString());
}However, the Dictionary object supports the KeyValuePair<T, U> type when using a foreach loop. This is due to the fact that the GetEnumerator method returns an IEnumerator, which in turn returns KeyValuePair<T, U> types, not DictionaryEntry types.
The KeyValuePair<T, U> type is well suited to be ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access