Dictionary And HashTable In C#




Hashtable and Dictionary

Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
See the following code:

Hashtable ht = new Hashtable();
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, null },
{ "Fv", "Five" },
{ 8.5F, 8.5 }
};

foreach (var key in ht.Keys )
{
Console.WriteLine("Key:{0}, Value:{1}",key , ht[key]);
}

Dictionary

C# Dictionary class is a generic collection of keys and values pair of data. The Dictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection.
See the following code:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
{1,"One"},
{2, "Two"},
{3,"Three"}
};

foreach (KeyValuePair<int, string> item in dict)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}



إرسال تعليق

أحدث أقدم