Generics, Dictionaries, and More - 4.10 Using foreach with Generic Dictionary Types
(Page 2 of 4 )
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 supportforeachusing theDictionaryEntrytype, 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, theDictionaryobject supports theKeyValuePair<T,U>type when using aforeachloop. This is due to the fact that theGetEnumeratormethod returns anIEnumerator, which in turn returnsKeyValuePair<T,U>types, notDictionaryEntrytypes.
TheKeyValuePair<T,U>type is well suited to be used when enumerating the genericDictionaryclass with aforeachloop. TheDictionaryEntryobject contains key and value pairs as objects, whereas theKeyValuePair<T,U>type contains key and value pairs as their original types, defined when creating theDictionaryobject. This boosts performance and can reduce the amount of code you have to write, as you do not have to cast the key and value pairs to their original types.
See Also
The “System.Collections.Generic.Dictionary Class,” “System.Collections.Generic. SortedList Class,” and “System.Collections.Generic.KeyValuePair Structure” topics in the MSDN documentation.
Next: 4.11 Constraining Type Arguments >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the C# 3.0 Cookbook, Third Edition, written by Jay Hilyard and Stephen Teilhet (O'Reilly, 2008; ISBN: 059651610X). Check it out today at your favorite bookstore. Buy this book now.
|
|