Wednesday, 18 April 2018

HashTable vs Dictionary


Hashtable and Dictionary are collection of data structures to hold data as key-value pairs.
1.  Dictionary is generic type,
2.  Hash table is not a generic type.
The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable.
The Dictionary class is a strongly types <T Key, T Value> and you must specify the data types for both the key and value.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace HashTable_and_Dictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            var hashtable = new Hashtable();           
            hashtable.Add(1, "One");
            hashtable.Add(2, "Two");
            hashtable.Add(3, "Three");
            hashtable.Add(4, "Four");
            hashtable.Add(5, "Five");
            hashtable.Add(6, "Six");
            hashtable.Add(7, "Seven");
            hashtable.Add(8, "Eight");
            hashtable.Add(9, "Nine");
            hashtable.Add(10, "Ten");                 
                   
            Console.WriteLine("\n\nHashTable Result\n-----------------");
            foreach (DictionaryEntry item_1 in hashtable)
            {
                Console.WriteLine("{0}, {1}", item_1.Key, item_1.Value);
            }
      
            Console.WriteLine("\n\nDictionary Result\n------------------");
            var dictionary = new Dictionary<int, string>();
            dictionary.Add(1, "One");
            dictionary.Add(2, "Two");
            dictionary.Add(3, "Three");
            dictionary.Add(4, "Four");
            dictionary.Add(5, "Five");
            dictionary.Add(6, "Six");
            dictionary.Add(7, "Seven");
            dictionary.Add(8, "Eight");
            dictionary.Add(9, "Nine");
            dictionary.Add(10, "Ten");

            var list = dictionary.Keys.ToList();
            list.Sort();

            foreach (var item in list)
            {
                Console.WriteLine("{0} : {1}", item, dictionary[item]);
            }

            Console.ReadLine();          
        }
    }
}


Result

HashTable Result

10. Ten

9. Nine
8. Eight
7. Seven
6.  Six
5. Five
4. Four
3. Three
2. Two
1. One

Dictionary Result
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten






No comments:

Post a Comment

Azure Service Bus Queue , Table - Send, Read

using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; ...