HashTable in C#.net


The Hashtable class implement the IDictionary interface. Therefore, each element in this collection is a key-and-value pair.
it is a collection class like an arraylist but stores the value in name,value or key,value based. arraylist also stores values in key,value pairs only where index is the key which is predefined.

hashtable
in case of hashtable these keys can be userdefined which can be specified by us explicitely as per our requirement…
A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, which is generated using a hash function and is based on the key of the element.

Hashtable should not allow Duplicate Keys, but allows Duplicate Values

Examples in Console Application:

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

namespace HashtableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();
            
            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //Displaying values in hashtable ht_employee
            Console.WriteLine("We Can display Hashtable Data in different Types of Logics");
            Console.WriteLine();
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:1 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(de.Value);
            }
            
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:3 If u know keys");
            Console.WriteLine("================================");
            Console.Write("EmpId" + "\t:");
            Console.WriteLine(ht_Employee["EmpId"]);
            Console.Write("EmpName" + "\t:");
            Console.WriteLine(ht_Employee["EmpName"]);
            Console.Write("Job" + "\t:");
            Console.WriteLine(ht_Employee["Job"]);
            Console.Write("Sal" + "\t:");
            Console.WriteLine(ht_Employee["Sal"]);
            Console.Write("Dept" + "\t:");
            Console.WriteLine(ht_Employee["Dept"]);
            Console.Write("Loc" + "\t:");
            Console.WriteLine(ht_Employee["Loc"]);

            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:2 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(ht_Employee[de.Key]);
            }
            Console.Read();
        }
    }
}

Output:

HashTableConsole

 

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

namespace Hashtable1
{
    class HashTableExtentions
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //If We add Existed key to hashtable it raises exception
            Console.WriteLine("==============================================================");
            Console.WriteLine("Add method Raise exception if new key is already in Hashtable");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            try
            {
                ht_Employee.Add("EmpId", 1000);
            }
            catch
            {
                Console.WriteLine("An element with Key = \"EmpId\" already exists.");
            }
            Console.WriteLine();

            //If we want to display values in discriptive manner
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", value = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();

            //How to change values associated with keys in hashtable
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", Oldvalue = {0}.", ht_Employee["EmpId"]);
            ht_Employee["EmpId"] = 101;
            Console.WriteLine("For key = \"EmpId\", Newvalue = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();
            Console.Read();

        }
    }
}

 

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

namespace Hashtable1
{
    class HashTableExtentions2
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //if we don't know wether the key is exist or not… we need to check and use that key
            //for this
            Console.WriteLine("==============================================================");
            Console.WriteLine("Checking wether key is exist or not");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (ht_Employee.ContainsKey("EmpName"))
            {
                Console.WriteLine("Value Exist for key = \"EmpName\": {0}", ht_Employee["EmpName"]);
            }
            Console.WriteLine();
            if(!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Value Doesn't Exist for key = \"SomeName\"");
            }
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Adding Value for SomeName key");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (!ht_Employee.ContainsKey("SomeName"))
            {
                ht_Employee.Add("SomeName", "Raju");
                Console.WriteLine("Value Exist for key = \"SomeName\": {0}", ht_Employee["SomeName"]);
            }
            Console.WriteLine();

            //To get the values only, use the Values property.
            ICollection valueColl = ht_Employee.Values;

            //Print values in valueColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print values in valueColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in valueColl)
            {
                Console.WriteLine("Value = {0}", s);
            }

            //To get the keys only, use the Keys property.
            ICollection keyColl = ht_Employee.Keys;

            //Print keys in keyColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print keys in keyColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in keyColl)
            {
                Console.WriteLine("Key = {0}", ht_Employee[s]);
            }

            // Use the Remove method to remove a key/value pair.
            Console.WriteLine("\nRemove(\"SomeName\")");
            ht_Employee.Remove("SomeName");

            if (!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Key \"SomeName\" is not found.");
            }
                
            Console.Read();
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s