The HashTable is based on the key value pair which is based on the hashing done. It uses the key to access the elements of the collection.
A hash table is used when you want a key value pair and want to access collection through key. Each item in this collection is key value pair.
The key pair have the following properties:
Property |
Description |
Count |
Gets the number of key-and-value pairs contained in the Hashtable. |
IsFixedSize |
Gets a value indicating whether the Hashtable has a fixed size. |
IsReadOnly |
Gets a value indicating whether the Hashtable is read-only. |
Item |
Gets or sets the value associated with the specified key. |
Keys |
Gets an ICollection containing the keys in the Hashtable. |
Values |
Gets an ICollection containing the values in the Hashtable. |
The key pair have the following methods:
Sr.No. |
Method |
1 |
public virtual void Add(object key, object value);
Adds an element with the specified key and value into the Hashtable.
|
2 |
public virtual void Clear();
Removes all elements from the Hashtable.
|
3 |
public virtual bool ContainsKey(object key);
Determines whether the Hashtable contains a specific key.
|
4 |
public virtual bool ContainsValue(object value);
Determines whether the Hashtable contains a specific value.
|
5 |
public virtual void Remove(object key);
Removes the element with the specified key from the Hashtable.
|
You can add the elements dynamically and delete the elements dynamically according to your need in it.
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("001", "Sukhdev Singh");
ht.Add("002", "Mahesh Bhatt");
ht.Add("003", "Tipu Sultaan");
ht.Add("004", "Maharana Pratap");
ht.Add("005", "Bhagat Singh");
ht.Add("006", "Chandrashekhar Azad");
if (ht.ContainsValue("Maharana Pratap"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
ht.Add("008", "Maharana Pratap");
}
// Get a collection of the keys.
ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
}
}
0 Comment(s)