Author - Dave Amour

Dave Amour has used computers for as long as he can remember and intially started out as an IT trainer delivering a range of IT courses but for the last 11 years has been focusing on the arena of web application development. He was worked for numerous companies over the years and is currently working for Audacs Software Ltd. Dave is also a keen squash player and an active and sucessful member of Experts Exchange

Please feel free to submit any constructive comments which you can do at the bottom of this page.

Dave may be available for programming tuition or consultancy work. Contact via dave@audacs.co.uk
Dave Amour - Click to view CV 

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:

Dictionary<string, int> dictionary = new Dictionary<string, int>();


So lets have a look at some code in action to see the way we work with a dictionary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DictionaryTests
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, System.Data.SqlClient.SqlConnection> myDictionary = new Dictionary<string, System.Data.SqlClient.SqlConnection>();
 
            myDictionary.Add("Development", new System.Data.SqlClient.SqlConnection("server=dev; uid=aaaa; pwd=bbb; database=cccc;"));
            myDictionary.Add("Test", new System.Data.SqlClient.SqlConnection("server=test; uid=aaaa; pwd=bbb; database=cccc;"));
            myDictionary.Add("Production", new System.Data.SqlClient.SqlConnection("server=production; uid=aaaa; pwd=bbb; database=cccc;"));
 
            foreach (KeyValuePair<string, System.Data.SqlClient.SqlConnection> connection in myDictionary)
            {
                Console.WriteLine(connection.Value.ConnectionString);
            }
 
            myDictionary.Remove("Test");
 
            Console.WriteLine();
           
            foreach (KeyValuePair<string, System.Data.SqlClient.SqlConnection> connection in myDictionary)
            {
                Console.WriteLine(connection.Value.ConnectionString);
            }
 
            Console.Read();
        }
    }
}


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 go 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

Leave a comment

Name

Email (optional and not disclosed)



Email address is not disclosed but just used to alert you of new posts if entered
Word CV
HTML CV
PDF CV
Text CV
CMS Lite
ETraining
Planet Health
Florida Health
the Date Shack
Taylors
Emcat
Emtex
Browne Jacobson
Alliance & Leicester
Baird Leisure
Swarfega
Creature Comforts
Rugeley Chess Club
Katnip
Katmaid
Dudley NHS
Contact Me
Current Status