Hashtable

Hashtable



Hash tables is a collection of associated keys & values which are arranged based on hash code of the key. It inherits IDictionary interface.the following code snippet shows simple demo of how to add/remove/clear elements to/from hash table by key.

Namespaces to be used
using system.collections
using system


namespace ConsoleApplication3
{

class Program
{
static void Main(string[] args)
{ //create object for hashtable
Hashtable a = new Hashtable(10);
//marks hashtable as thread safe
Hashtable.Synchronized(a);
//add memebers to the hash table
a.Add(100, "arrays");
a.Add(200, "classes");
//print values to console
foreach (DictionaryEntry d in a)
{
Console.WriteLine(d.Value);
}
//remove members with hash code 100
a.Remove(100);
//remove meembers with hashcode 200
a.Remove(200);
foreach (DictionaryEntry d in a)
{
Console.WriteLine(d.Value);
}
//removing all the items in hash table
a.Clear();
foreach (DictionaryEntry d in a)
{
Console.WriteLine(d.Value);
Console.WriteLine("no data found...");
}

Console.WriteLine("no data found..");
}
}
}



Explanation:

-->the items r added to the hashtable by means of hashcode of key.
-->the items r removed from hashtable by means of hashcode of key
--->the all items can be removed from hashtavble.
-->we can marh hashtable as thread safe


Comments

Author: Sanjay20 Jul 2010 Member Level: Silver   Points : 2

namespace hashtable
{
class sanjay
{
static void Main(string[] args)
{
Hashtable objhashtable = new Hashtable();//syntex for create the hshtable

//Adding the value in hashtable by using the object
objhashtable.Add("AU01", "John");
objhashtable.Add("AU02", "Smit");
Console.WriteLine("Readonly :"+objhashtable.IsReadOnly);

//Count the value of hashtable
Console.WriteLine("Count:"+objhashtable.Count);

//Show the list of added value
IDictionaryEnumerator objidic = objhashtable.GetEnumerator();
Console.WriteLine("List of author:\n");
Console.WriteLine("Author Id\t Name");
while (objidic.MoveNext())
{
Console.WriteLine(objidic.Key+"\t\t"+objidic.Value);
}
if (objhashtable.Contains("AU01"))
{
Console.WriteLine("\nList contain outher with id AU01");
}
else
{
Console.WriteLine("\nList does not contain author with id AU01");
}
}
}
}


-Sanjay D Tank.

Author: Radhika21 Jul 2010 Member Level: Bronze   Points : 0

testing



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: