Working with Dictionary Collections in C#

Leave a Comment
Another very useful generic collection is the Dictionary, which works with key/value pairs. There is a non-generic collection, called a Hashtable that does the same thing, except that it operates on type object. However, as explained earlier in this lesson, you want to avoid the non-generic collections and use thier generic counterparts instead. The scenario I'll use for this example is that you have a list of Customers that you need to work with. It would be natural to keep track of these Customers via their CustomerID. The Dictionary example will work with instances of the following Customer class:
     public class Customer
    {
        public Customer(int id, string name)
        {
            ID = id;
            Name = name;
        }
        private int m_id;
        public int ID
        {
            get { return m_id; }
            set { m_id = value; }
        }
        private string m_name;
        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }
    }

The Customer class above has a constructor to make it easier to initialize. It also exposes it's state via public properties. It isn't very sophisticated at this point, but that's okay because its only purpose is to help you learn how to use a Dictionary collection.  The following example populates a Dictionary collection with Customer objects and then shows you how to extract entries from the Dictionary:
    Dictionary<int, Customer> customers = new Dictionary<int, Customer>();
    Customer cust1 = new Customer(1, "Cust 1");
    Customer cust2 = new Customer(2, "Cust 2");
    Customer cust3 = new Customer(3, "Cust 3");
    customers.Add(cust1.ID, cust1);
    customers.Add(cust2.ID, cust2);
    customers.Add(cust3.ID, cust3);
    foreach (KeyValuePair<int, Customer> custKeyVal in customers)
    {
        Console.WriteLine(
            "Customer ID: {0}, Name: {1}",
            custKeyVal.Key,
            custKeyVal.Value.Name);
    }

The customers variable is declared as a Dictionary<int, Customer>.  Considering that the formal declaration of Dictionary is Dictionary<TKey, TValue>, the meaning of customers is that it is a Dictionary where the key is type int and the value is type Customer. Therefore, any time you add an entry to the Dictionary, you must provide the key because it is also the key that you will use to extract a specified Customer from the Dictionary.

I created three Customer objects, giving each an ID and a Name. I'll use the ID as the key and the entire Customer object as the value. You can see this in the calls to Add, where custX.ID is added as the key (first parameter) and the custX instance is added as the value (second parameter).

Extracting information from a Dictionary is a little bit different. Iterating through the customers Dictionary with a foreach loop, the type returned is KeyValuePair<TKey, TValue>, where TKey is type int and TValue is type Customer because those are the types that the customers Dictionary is defined with.

Since custKeyVal is type KeyValuePair<int, Customer> it has Key and Value properties for you to read from. In our example, custKeyVal.Key will hold the ID for the Customer instance and custKeyVal.Value will hold the whole Customer instance. The parameters in the Console.WriteLine statement demonstrate this by printing out the ID, obtained through the Key property, and the Name, obtained through the Name property of the Customer instance that is returned by the Value property.

The Dictionary type is handy for those situations where you need to keep track of objects via some unique identifier. For your convenience, here's below code shows how both the List and Dictionary collections work.
using System;
using System.Collections.Generic;
public class Customer
{
    public Customer(int id, string name)
    {
        ID = id;
        Name = name;
    }
    private int m_id;
    public int ID
    {
        get { return m_id; }
        set { m_id = value; }
    }
    private string m_name;
    public string Name
    {
        get { return m_name; }
        set { m_name = value; }
    }
}
class Program
{
    static void Main(string[] args)
    {
        List<int> myInts = new List<int>();
        myInts.Add(1);
        myInts.Add(2);
        myInts.Add(3);
        for (int i = 0; i < myInts.Count; i++)
        {
            Console.WriteLine("MyInts: {0}", myInts[i]);
        }
        Dictionary<int, Customer> customers = new Dictionary<int, Customer>();
        Customer cust1 = new Customer(1, "Cust 1");
        Customer cust2 = new Customer(2, "Cust 2");
        Customer cust3 = new Customer(3, "Cust 3");
        customers.Add(cust1.ID, cust1);
        customers.Add(cust2.ID, cust2);
        customers.Add(cust3.ID, cust3);
        foreach (KeyValuePair<int, Customer> custKeyVal in customers)
        {
            Console.WriteLine(
                "Customer ID: {0}, Name: {1}",
                custKeyVal.Key,
                custKeyVal.Value.Name);
        }
        Console.ReadKey();
    }
}

0 comments:

Post a Comment