
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
274
|
Chapter 4: Generics
// Create object array to hold copied information from Dictionary object.
KeyValuePair<int, string>[] objs = new KeyValuePair<int, string>[numbers.Count];
// Calling CopyTo on a Dictionary
// Copies all KeyValuePair objects in Dictionary object to objs[]
((IDictionary)numbers).CopyTo(objs, 0);
// Display all key/value pairs in the objs[].
foreach (KeyValuePair<int, string> kvp in objs)
{
Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
}
Calling CopyTo on the Dictionary object involves setting up an array of
KeyValuePair<T,U> objects, which will end up holding all the KeyValuePair<T,U>
objects within the Dictionary object after the CopyTo method is called. Next, the
numbers Dictionary object is cast to an IDictionary type so that the CopyTo method
may be called. Once the
CopyTo method is called, the objs array will contain copies of
all the
KeyValuePair<T,U> objects that are in the original numbers object. Note that
iteration of the
objs array, using a foreach loop, is done in the same fashion as with
the
numbers object.
See Also
See the “System.Collections.Hashtable Class” and “System.Collections.Generic.
Dictionary Class” topics in the MSDN documentation.
4.11 Using foreach with Generic Dictionary Types
Problem
You need to enumerate the elements within