The Dictionary<K, V> Type

The C# has a number of object types that offer more functionality thatn your standard primitive types. We will look at the List, Set, Dictionary, and File types.

LIst, Set, and Dictionary are known as Generic types (more on this in a further course).

Arrays are limited by their rigidity. You have to create them of a fixed size. You cannot alter their size once they have been created. The only way to access elements is throuh an zero based index.

The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.

As its name suggests, items are added to the dictionary in a key value pairing. Items can then be searched for and retrieved using the key (fastest option) or by value (slowest option).

Example

Result

Example

Result

Dictionary<int, string> employees = new Dictionary<int, string>(); employees.Add(749365, "Selvyn Wright"); employees.Add(445576, "Micheal Franks"); employees.Add(324572, "Fiona James"); foreach(KeyValuePair<int, string> kvp in employees) { Console.WriteLine($"Employee: {kvp.Key}/{kvp.Value}"); }

Create the Dictionary and bind it to two types, an int for the key, and a string for the value.

The Add() method takes two parameters. These must match the two types that were used when creating the generic Dictionary class. For other methods check the API guide paramter types. The first parameter is the key and the second is the value. This pair of items are bound together through an internal type called KeyValuePair<K,V>.

In the foreach satement, each item in employees is projected one by one into the kvp variable. Each time a value from employees is projected into kvp the code block is executed with the current value in age. This repeats until all items within employees have been exhausted.

The kvp variable is of the type KeyValuePair<K, V>. As its name implies it’s an associative class that binds a key value to a store value. The Dictionary object maintains a collecrtion of KeyValuePair objects. A new KeyValuePair instance is created each time the Add() method is called with a key that does not already exist in the Dictionary.

Dictionary<int, string> employees = new Dictionary<int, string>(); employees.Add(749365, "Selvyn Wright"); employees.Add(445576, "Micheal Franks"); employees.Add(324572, "Fiona James");

Modify the code to

Dictionary<int, string> employees = new Dictionary<int, string>(); try { employees.Add(749365, "Selvyn Wright"); employees.Add(445576, "Micheal Franks"); employees.Add(324572, "Fiona James"); employees.Add(445576, "Micheal Franks"); } catch (ArgumentException ae) { Console.WriteLine($"Attempt to add duplicate Key - \"{ae.Message}\""); }

 

The Add() method will throw an exception if the same key is used more than once to add an item to the collection.

If the above code is modified to so that one on the entres added twice, the following error will occurr

With the second version, the try... catch block (you learn more about this later in the course) protects the block of code that may exit abruptly. Execution is transferred to the code block after the catch( ArgumentException ae )

 

 

There are a number of ways of accessing the elements of Dictionary, using the index operator [], or using the TryGet() and ContainsKey() methods.

Example

Result

Example

Result

Accessing Dictionary elements using the index operator [].

The array of employee numbers will be used to create the Dictionary elements access them.

 

 

Iteratoe over the Dictionary elements using a simple counter.

Access each element using employees[empIDs[i]]. y simply using the [] operator in a read context, value passed into [] is used a key to locate an element. If it exists it is returned. If the key is not valid, KeyNotFoundException is thrown.

Using ContainsKey() to probe if a key exists before accessing it

 

 

 

We puprosely modify one of the employee IDs by incrementing it by one. This will cause it become an invalid key search in the Dictionary.

 

Using the ContainsKey() method we validate if the key exists

Using TryGetValue() to probe and return a value if the key exists in the Dictionary.

 

 

 

We puprosely modify one of the employee IDs by incrementing it by one. This will cause it become an invalid key search in the Dictionary.

 

Set up a variable to hold the retrieved value if it exists

Probe the Dictionary to see if the key exists. If it does TryGetValue() returns a true and the out parameter employeeName is populated with the value from the dictionary.