Recipe4.11.Using foreach with Generic Dictionary Types


Recipe 4.11. 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>(); 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); } 

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:

 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.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net