Dictionary classes in C#

Hashtable class stores the item in key-value pair. Each item is a key/value pair stored in a DictionaryEntry object. It uses the key to access the elements in the collection.

You can add any type of key and value in Hashtable by using Add() method.

public virtual void Add(object key, object value);

Because each item stored as key-value pair, that’s why you cannot access element like, we access in case of ArrayList. In Hashtable element type is DictionaryEntry.

Creating a Hashtable

Hashtable empTable = new Hashtable();

Adding Items to a Hashtable

You can use Add() method or indexer to add item as key-value pair in Hashtable. The following code adds three items to hashtable.

empTable.Add("1", "Raj");
empTable.Add("2", "James");


OR

empTable[3]= "Shiva";

Retrieving an Item Value from Hashtable

The following code returns the value of "1" key:

string name = empTable["1"].ToString();

Removing Items from a Hashtable

The Remove method removes an item from a Hashtable.

empTable.Remove("3");

Looking through all Items of a Hashtable

The following code reads the values of all items of a hashtable.

// Loop through all items of a Hashtable
foreach (DictionaryEntry obj in empTable)
{
     Console.WriteLine("\t{0}:\t{1}", obj.Key, obj.Value);
}


A DictionaryEntry class works as a container containing a Key and a Value.

Example

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable empTable = new Hashtable();
            empTable.Add("1", "Raj");
            empTable.Add("2", "James");
            empTable[3]= "Shiva";
           
            foreach (DictionaryEntry obj in empTable)
                Console.WriteLine("\t{0}:\t{1}", obj.Key, obj.Value);
            Console.ReadLine();
        }
    }
}


Execute the above code you will get the following output:

        2:      James
        1:      Raj
        3:      Shiva

It is not necessary that Hashtable will give you the result in ordered manner with respect to key. See the above output.

Important points of Hashtable

  • Hashtable stores item in key-value pairs of any data type.
  • The Hashtable key cannot be null but the value can be null.
  • Hashtable retrieves an item by comparing the hashcode of keys.
  • DictionaryEntry class is used with foreach loop to iterate Hashtable.
  • Hashtable class is a very efficient collection for huge number of elements.

SortedList Class

SortedList class is a dictionary class that stores key/value pairs in sorted order, based on the value of the keys.

Important Properties of SortedList

PropertyDescription
CapacityGets or sets the number of elements in the SortedList
CountGets the number of elements contained in the SortedList.
IsFixedSizeIt returns Boolean value. True- if the size is Fixed, else False.
ItemGets or sets the element at the specified key in the SortedList.
KeysGet list of keys of SortedList.
ValuesGet list of values in SortedList


Important Methods of SortedList

MethodsDescription
void Add(object key, object value)Add key-value pairs into SortedList.
void Remove(object key)Removes item from SortedList according to key.
void RemoveAt(int index)Removes item at the specified index.
bool Contains(object key)Checks whether key exists or not in SortedList.
object GetByIndex(int index)Returns the item specified by index
int IndexOfKey(object key)Returns an index of specified key


Example

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList list = new SortedList();
            list.Add(3, "Third");
            list.Add(4, "Fourth");
            list.Add(1, "First");
            list.Add(5, "Fifth");
            list.Add(2, "Second");

            foreach(DictionaryEntry obj in list)
            {
                Console.WriteLine("\t{0}:\t{1}", obj.Key, obj.Value);
            }
            Console.WriteLine("Capacity      =: " +list.Capacity);
            Console.WriteLine("Count         =: " +list.Count);
            Console.WriteLine("ContainsKey   =: " + list.ContainsKey(3));
            Console.WriteLine("ContainsValue =: " + list.ContainsValue(3));
            Console.WriteLine("GetByIndex    =: " + list.GetByIndex(1));

            Console.WriteLine("IndexOfKey    =: " + list.IndexOfKey(2));
            Console.WriteLine("IndexOfValue  =: " + list.IndexOfValue("Third"));
            Console.WriteLine("IsFixedSize   =: " + list.IsFixedSize);
               
            Console.ReadLine();
        }
    }
}


You can add key of any data type in SortedList, but always remember that you cannot add keys of different data types in the same SortedList.

Example

SortedList list = new SortedList();

list.Add(2, "Second");
// It will give run time exception. Item has already been added. Key in dictionary:2
list.Add(2, "MyValue");


Key things of SortedList

  • SortedList stores keys and values of any data types.
  • SortedList stores the key-value pairs in ascending order of the key.
  • Key must be unique and cannot be null.
  • For accessing value, you need to be cast to appropriate data type.

SpecializedDictionary

ListDictionary

ListDictionary, HybridDictionary, OrderedDictionary are specialized dictionary so you must use namespace “System.Collections.Specialized” in your program.

The ListDictionary class is a very efficient collection for small collections. Its working is same as Hashtable but for less than ten elements, ListDictionary is better. It is not necessary that item in the ListDictionary are in order.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ListDictionary list = new ListDictionary();
            list.Add(3, "Third");
            list.Add(4, "Fourth");
            list.Add(1, "First");
            list.Add(5, "Fifth");
            list.Add(2, "Second");           

            foreach(DictionaryEntry obj in list)
            {
                Console.WriteLine("\t{0}:\t{1}", obj.Key, obj.Value);
            }          
            Console.WriteLine("Count         =: " + list.Count);
            Console.WriteLine("IsFixedSize   =: " + list.IsFixedSize);          
            Console.ReadLine();
        }
    }
}


HybridDictionary

ListDictionary is efficient for small collection and HashTable is efficient for large collection. But what if you do not know the size of collection at early stage? In this situation HybridDictionary comes in picture.

As its name suggests that it is combination of dictionary, So It is implemented as a ListDictionary in initial stage (item less than ten) and when the list becomes too large it convert itself into a Hashtable internally.

Example

using System;
using System.Collections;
using System.Collections.Specialized;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HybridDictionary list = new HybridDictionary();
            list.Add(1, "First");
            list.Add(2, "Second");
            list.Add(3, "Third");
            list.Add(4, "Fourth");           
            list.Add(5, "Fifth");                
            foreach(DictionaryEntry obj in list)
            {
                Console.WriteLine("\t{0}:\t{1}", obj.Key, obj.Value);
            }          
            Console.WriteLine("Count         =: " + list.Count);                     
            Console.ReadLine();
        }
    }
}


OrderedDictionary

An OrderedDictionary is much like a Hashtable but it has some extra method. You can access the elements by index.