Other DictionaryBase Methods
There are two other methods that are members of the DictionaryBase class:
CopyTo and GetEnumerator. We discuss these methods in this section.
The CopyTo method copies the contents of a dictionary to a one-
dimensional array. The array should be declared as a DictionaryEntry array,
though you can declare it asObject and then use theCType function to convert
the objects to DictionaryEntry.
The following code fragment demonstrates howto use the CopyTomethod:
IPAddresses myIPs = new IPAddresses("c:\ips.txt");
DictionaryEntry[] ips = _
new DictionaryEntry[myIPs.Count-1];
myIPs.CopyTo(ips, 0);
The formula used to size the array takes the number of elements in the dic-
tionary and then subtracts one to account for a zero-based array. The CopyTo
method takes two arguments: the array to copy to and the index position to
start copying from. If you want to place the contents of a dictionary at the
end of an existing array, for example, you would specify the upper bound of
the array plus one as the second argument.
Once we get the data from the dictionary into an array, we want to work
with the contents of the array, or at least display the values. Here’s some code
to do that:
for(inti=0;i<= ips.GetUpperBound(0); i++)
Console.WriteLine(ips[i]);
Unfortunately, this is not what we want. The problem is that we’re storing
he data in the array as DictionaryEntry objects, and that’s exactly what we
see. If we use the ToString method:
Console.WriteLine(ips[ndex]ToString())
we get the same thing. In order to actually view the data in a DictionaryEntry
object,we have to use either the Key property or the Value property, depending
on if the object we’re querying holds key data or value data. So how do we
know which is which? When the contents of the dictionary are copied to the
array, the data is copied in key–value order. So the ?rst object is a key, the
second object is a value, the third object is a key, and so on.
Now we can write a code fragment that allows us to actually see the data:
for(inti=0;i<= ips.GetUpperBound(0); i++) {
Console.WriteLine(ips[index].Key);
Console.WriteLine(ips[index].Value);
}
No comments:
Post a Comment