Collection Classes in .net - the Dictionary & SortedDictionary
This is the fifth part of an article on collection classes in .net with C#. This part covers the Dictionary.
For the first part see http://www.audacs.co.uk/ViewPage.aspx?PageID=512
For the next part on the Stack see http://www.audacs.co.uk/ViewPage.aspx?PageID=517
The dictionary collection was added to the .net framework in version 2.0. Like the hashtable it stores objects as a colletion of key, value pairs. The big difference with the dictionary though is that it is a generic class and so at the point of declaration the key and value types must be specified -eg:
So lets have a look at some code in action to see the way we work with a dictionary.
So this is pretty simple. We create an instance of a Dictionary which is defined to contain a string and a Connection object.
We then add 3 items to the dictionary and iterate over them using a foreach statement. This utilises the fact that the items in the dictionary are of a type called KeyValuePair. KeyValuePair is actually a struct. We then output the connection string to the console. This shows just one way of iterating over the collection but there are others which you could use such as iterating over the keys and then using the key to retrieve each item.
We then remove and item and then output the connection strings again to show that the removal worked ok.
There are of course many other properties and methods of interest but and have a look at those yourself.
There is a class very simillar to the Dictionary which is called a SortedDictionary. Normal dictionaries keep items in the order they were inserted but a SortedDictionary keeps items sorted by the key based on the key's comparer.
There are of course advantages and disadvantages of using each of these. The following should be considered when making a choice on which of these classes to use.
Dictionary
Insertion time and searching time should be considered. Since elements are not automatically sorted, inserting elements is faster.
Similarly because elements are not sorted, it makes searching more complicated, meaning searching is slower.
SortedDictionary
In a SortedDictionary elements are sorted when they are added, making insertion times slower.
However elements are kept in sorted order therefore searching can be done with binary search techniques, meaning searching is faster.
For the next part on the Stack see http://www.audacs.co.uk/ViewPage.aspx?PageID=517