Basic Collections - Dictionaries
(Page 5 of 6 )
Dictionaries
A list provides a zero-based integer index. For some applications, this is all that's necessary. However, it's often necessary to have other types be used as indexes or to have a non-zero-based integer system. A dictionary provides this functionality, allowing the user to define the types for both the indexes, which are known as keys, and the values.
For example, suppose we have a list of names. Each name represents a person with a room in some sort of complex (an office complex, an apartment complex – use your imagination), and each room has a number. If we want to store the room number of each person, we can use a Dictionary. The keys can be the names of the people, and the values can be their room numbers. The keys would be strings, and the values would be integers. Here, we define a Dictionary modeled after our example:
Dictionary<string, int> rooms = new Dictionary<string, int>();
A non-generic dictionary is known as a Hashtable.
Notice how we pass in two types. The first is the key type, and the second is the value type.
The Add method can be used to add entries into a Dictionary. Add takes two arguments: the key for the given entry and the value for the given entry. Here, we add two entries to our Dictionary:
rooms.Add("John Smith", 101);
rooms.Add("Jane Doe", 106);
It's also possible to skip the Add method and assign values directly to new keys. This is also how the values of existing keys can be re-assigned, and it gives away how individual entries may be accessed:
rooms["Daniel Noname"] = 115;
We can remove an entry with the Remove method, which accepts as its argument the key of the entry to be removed:
rooms.Remove("John Smith");
Dictionary, like List, Queue and Stack, also supports a Clear method to remove all entries.
Enumerating over the entries in a Dictionary is slightly different from enumerating over the values in a List, Queue, Stack or array. This is because every element in a Dictionary has two values associated with it. To iterate over both the key and the value of every element in a Dictionary, the KeyValuePair generic type is used. Here, we iterate over our Dictionary:
foreach (KeyValuePair<string, int> kvp in rooms)
{
Console.WriteLine("{0}: Room {1}", kvp.Key, kvp.Value);
}
The above code will loop through each element in our Dictionary and write the keys and values of the entries to the console. Notice how KeyValuePair mirrors our Dictionary in the types with which it's associated.
Of course, sometimes it's not necessary to know both the key and the value of each entry. Dictionary supports this by containing two properties: Keys and Values. Keys returns a special collection called a KeyCollection, and Values returns a special collection called a ValueCollection. We can iterate over either of these as we would an array:
foreach (string occupant in rooms.Keys)
{
Console.WriteLine(occupant);
}
foreach (int roomNumber in rooms.Values)
{
Console.WriteLine("Room {0}", roomNumber);
}
To see whether a Dictionary contains a given key or a given value, the ContainsKey and ContainsValue methods can be used, both of which, as with the similar Contains method in the collections covered previously, return a boolean value:
bool johnSmithFound = rooms.ContainsKey("John Smith");
bool room106Found = rooms.ContainsValue(106);
The number of elements in a Dictionary can be obtained using the Count property:
int numberOfRooms = rooms.Count;
Next: Conclusion >>
More ASP.NET Articles
More By Peyton McCullough