17.5. Dictionaries


A dictionary is a collection that associates a key with a value. A language dictionary, such as Webster's, associates a word (the key) with its definition (the value).

To see the benefit of dictionaries , start by imagining that you want to keep a list of the state capitals. One approach might be to put them in an array:

 Dim stateCapitals(50) As String 

The stateCapitals array will hold 50 state capitals. Each capital is accessed as an offset into the array. For example, to access the capital for Arkansas, you need to know that Arkansas is the fourth state in alphabetical order:

 Dim capitalOfArkansas As String = stateCapitals(4) 

It is inconvenient, however, to access state capitals using array notation. After all, if I need the capital for Massachusetts, there is no easy way for me to determine that Massachusetts is the 21st state alphabetically.

It would be far more convenient to store the capital with the state name. A dictionary allows you to store a value (in this case, the capital) with a key (in this case, the name of the state).

A .NET Framework generic dictionary can associate any kind of key (string, integer, object, etc.) with any kind of value (string, integer, object, etc.). Typically, of course, the key is fairly short, the value fairly complex.

The most important attributes of a good dictionary are that it is easy to add values and that it is quick to retrieve values and some of the most important properties methods of the Dictionary class are shown in Table 17-5.

Table 17-5. Dictionary methods and properties

Method or property

Purpose

Count

Public property that gets the number of elements in the Dictionary.

Item

The indexer for the Dictionary.

Keys

Public property that gets a collection containing the keys in the Dictionary. (See also Values.)

Values

Public property that gets a collection containing the values in the Dictionary. (See also Keys.)

Add

Adds an entry with a specified Key and Value.

Clear

Removes all objects from the Dictionary.

ContainsKey

Determines whether the Dictionary has a specified key.

ContainsValue

Determines whether the Dictionary has a specified value.

GetEnumerator

Returns an enumerator for the Dictionary.

GetObjectData

Implements ISerializable and returns the data needed to serialize the Dictionary.

Remove

Removes the entry with the specified Key.


The key in a Dictionary can be a primitive type, or it can be an instance of a user-defined type (an object). Objects used as keys for a Dictionary must implement GetHashCode as well as Equals. In most cases, you can simply use the inherited implementation from Object.

17.5.1. IDictionary IDictionary

Dictionaries implement the IDictionary<K,V> interface (where K is the key type and V is the value type).

Example 17-7 demonstrates adding items to a Dictionary and then retrieving them.

Example 17-7. The Item property as offset operators
 Module Module1     Sub Main(  )       Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)       dict.Add("Alabama", "Montgomery")       dict.Add("Alaska", "Juneau")       dict.Add("Arizona", "Phoenix")       dict.Add("Arkansas", "Little Rock")       dict.Add("California", "Sacramento")       dict.Add("Colorado", "Denver")       dict.Add("Connecticut", "Hartford")       dict.Add("Delaware", "Dover")       dict.Add("Florida", "Tallahassee")       dict.Add("Georgia", "Atlanta")       dict.Add("Hawaii", "Honolulu")       dict.Add("Idaho", "Boise")       dict.Add("Illinois", "Springfield")       dict.Add("Iowa", "Des Moines")       dict.Add("Kansas", "Topeka")       dict.Add("Kentucky", "Frankfort")       dict.Add("Louisiana", "Baton Rouge")       dict.Add("Maine", "Augusta")       dict.Add("Maryland", "Anapolis")       dict.Add("Massachusetts", "Boston")       dict.Add("Michigan", "Lansing")       dict.Add("Minnesota", "St. Paul")       dict.Add("Mississippi", "Jackson")       dict.Add("Missouri", "Jefferson City")       dict.Add("Montana", "Helena")       dict.Add("Nebraska", "Lincoln")       dict.Add("Nevada", "Carson City")       dict.Add("New Hampshire", "Concord")       dict.Add("New Jersey", "Trenton")       dict.Add("New Mexico", "Santa Fe")       dict.Add("New York", "Albany")       dict.Add("North Carolina", "Raleigh")       dict.Add("North Dakota", "Bismark")       dict.Add("Ohio", "Columbus")       dict.Add("Oklahoma", "Oklahoma City")       dict.Add("Oregon", "Salem")       dict.Add("Pennsylvania", "Harrisburg")       dict.Add("Rhode Island", "Providence")       dict.Add("South Carolina", "Columbia")       dict.Add("South Dakota", "Pierre")       dict.Add("Tennessee", "Nashville")       dict.Add("Texas", "Austin")       dict.Add("Utah", "Salt Lake City")       dict.Add("Vermont", "Montpelier")       dict.Add("Washington", "Olympia")       dict.Add("West Virginia", "Charleston")       dict.Add("Wisconsin", "Madison")       dict.Add("Wyoming", "Cheyenne")       ' access a state       Console.WriteLine("The capital of Massachusetts is {0}", _          dict("Massachusetts"))     End Sub End Module Output: The capital of Massachussetts is Boston 

Example 17-7 begins by instantiating a new Dictionary. The key and the value are both declared to be strings.

I got a bit carried away and added the key/value pairs for all 50 states. The key is the state name, the value is the capital (often the values associated with a key will be more complex than simple strings) then accessed the capital of Massachusetts, using the string Massachusetts as the key, and retrieving the string Boston as the value.

If you use a reference type as a key you must be careful not to change the value of the key object once you are using it in a Dictionary. (This can happen by changing another reference to the same object and inadvertently changing the value of the key)

If, for example, you were using an Employee object as a key, changing the employeeID in another reference to the same object would create problems in the Dictionary if that property were used by the Equals or GetHashCode methods; the Dictionary consults these methods.




Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

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