C# Dictionary & Hashtable
C# Dictionary (Fixed Type Key &Value )
using System.Collections.Generic;
Dictionary<KeyType, ValueType> dictName = new Dictionary<KeyType, ValueType>();
Dictionary<int, string> dictName = new Dictionary<int, string>();
dictName.Add(1, "Zakir");
dictName.Add(2, "Zahid");
dictName.Add(3, "Rakib");
dictName.Add(4, "Pranto");
dictName.Remove("Rakib");
//Or
dictName.Remove(3);
foreach (var item in dictName)
{
Console.WriteLine(item.Key + " " + item.Value);
}
//string myString = "";
string myString = string.Empty;
if (dictName.TryGetValue(2, out myString))
{
Console.WriteLine(myString);
}
dictName.TryGetValue(2, out myString) means Try searching for value by key number 2. If you find it, put it in "myString".
C# Hashtable (Dynamic Type Key & Value )
using System.Collections;
Hashtable hName = new Hashtable();
hName.Add(1, "Zakir"); //key=int, value=string
hName.Add("Zahid", "Production Officer"); // key=string, value=string
hName.Add("Keya", 16); //key=string, value=int
hName.Add(3.5, "Marvel"); //key=float, value=string
hName.Remove("Marvel");
//Or
hName.Remove(3.5);
if (hName.Contains("keya"))
{
Console.WriteLine("Found");
}
foreach (var item in hName.Keys)
{
Console.WriteLine(item);
}
foreach (var item in hName.Values)
{
Console.WriteLine(item);
}
foreach (DictionaryEntry item in hName)
{
Console.WriteLine(item.Key +" "+item.Value);
}
Notice, here data type is DictionaryEntry
The order at the output of the loop is not maintained. This means randomly showing the output.
In conclusion, C# Dictionary and Hashtable are both collection classes used to store key-value pairs in the .NET framework. However, there are some key differences between the two. Dictionary is a generic class that offers better performance and provides more features compared to Hashtable, such as type safety and built-in methods for sorting and searching. On the other hand, Hashtable is a non-generic class and can store keys and values of any object type, but is slower than Dictionary. It's recommended to use Dictionary whenever possible and only use Hashtable when compatibility with older code is required.
Post a Comment