Using foreach with Generic Dictionary Types

Using foreach with Generic Dictionary Types


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.


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>();
	myStringDict.Add(1, "Foo");
	myStringDict.Add(2, "Bar");
	myStringDict.Add(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);


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:

	foreach (DictionaryEntry de in myDict)
	    Console.WriteLine("key " + de.Key);
	    Console.WriteLine("Value " + de.Value);

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 used when enumerating the generic Dictionary class with a foreach loop. The DictionaryEntry object contains key and value pairs as objects, whereas the KeyValuePair<T,U> type contains key and value pairs as their original types, defined when creating the Dictionary object. 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

See the "System.Collections.Generic.Dictionary Class," "System.Collections.Generic. SortedList Class," and "System.Collections.Generic.KeyValuePair Structure" topics in the MSDN documentation.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows