C# Programming Language: Hashtables

Creating Hashtables

using System.Collections;
Hashtable myHT = new Hashtable();

Adding Elements Into The HashTable

Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
foreach(var key in myHT.Keys)
{
Console.WriteLine(key + ": " + myHT[key]);
}
Output:
4: Four
17: Seventeen
1: One

Checking The Size of The Hashtable

Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
Console.WriteLine(myHT.Count);
Output:
3

Checking if The Hashtable Contains a Specific Key

Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
Console.WriteLine(myHT.ContainsKey(1));
Console.WriteLine(myHT.ContainsKey(2));
Output:
True
False

Checking if The Hashtable Contains a Specific Value

Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
Console.WriteLine(myHT.ContainsValue("One"));
Console.WriteLine(myHT.ContainsValue("Two"));
Output:
True
False

Removing an Element From a Hashtable

Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
myHT.Remove(1);
foreach(var key in myHT.Keys)
{
Console.WriteLine(key + ": " + myHT[key]);
}
Output:
4: Four
17: Seventeen

Clearing out a Hashtable

Hashtable myHT = new Hashtable();
myHT.Add(1, "One");
myHT.Add(4, "Four");
myHT.Add(17, "Seventeen");
myHT.Clear();
foreach(var key in myHT.Keys)
{
Console.WriteLine(key + ": " + myHT[key]);
}
Output:

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

GEE Tutorial #28: How to use your local computer as a web server for hosting Earth Engine Apps?

ESP32-Project 7: ESP32 Bluetooth

Deploy .Net Core App to Heroku

Flutter in a Weekend: Friday - Installation

Best productivity tools for web developers

Introducing the $HELIOS token.

Pimp out your MacTerminal w/ ZSH

Run Python codes/Develop ML models using WSL (Windows 10)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jesse L

Jesse L

More from Medium

How to use better GroupBy in LINQ ?

C# Programming Language: Queue

C# extension methods

Scoped, Transient and Singleton