Friday, 20 September 2013

Hashtable in C#

 
Hi frnds, you couldn't believe about hashtable concept in c#.
 
I don't know ,how would I missed it. But its very helpful while searching for generic collections related techniques. I just viewed it , but never used it before.
 
So I am sharing some ways to use it at your place.
 
 
Members of hastable :  
 
Key :-  Unique value which can be number or character
 
Value :- Value you want to store on particular key
 
 
The example adds 15 distinct integer keys, with one string value each, to the Hashtable object.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HashTableDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            string _concat = "A";
            Hashtable _hash = new Hashtable(15);
            for (int _key = 0; _key < 15; _key++)
            {
                _concat = _concat + _key;
                _hash.Add(_key, _concat.ToString());
                Console.WriteLine("Key {0} ,Value {1} ", _key, _concat.ToString());
            }
            Console.ReadLine();
        }
    }
 
Output : Please check at u r side.....
 
 
Contains  method in Hastable:
 
Instance methods on the Hashtable ,which returns true if the key is found, regardless of the value.
 
Example: 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HashTableDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable hashtable = GetHashtable();
            // See if the Hashtable contains this key.
            Console.WriteLine(hashtable.ContainsKey("Perimeter"));
            // Test the Contains method. It works the same way.
            Console.WriteLine(hashtable.Contains("Area"));
            // Get value of Area with indexer.
            int value = (int)hashtable["Area"];
            // Write the value of Area.
            Console.WriteLine(value);
            Console.ReadLine();
        }
        static Hashtable GetHashtable()
        {           
            Hashtable hashtable = new Hashtable();
            hashtable.Add("Area", 1000);
            hashtable.Add("Perimeter", 55);
            hashtable.Add("Mortgage", 540);
            return hashtable;
        }
    }
}
 [Note :  But if we compare Hastable with Dictionary ... we found hashtable results slower than Dictionary. ]
 
 

No comments:

Post a Comment