Home
Quick CheatSheet C# HashTables
Note - it seems Dictionaries are a little quicker and a little less memory intensive than HashTables. This is because we kind of "FIX" the type when we create the Dictionary - eg
Dictionary<string, string> myDict = new Dictionary<string, string>();
using System.Collections;
public class Program
{
//Note - it seems Dictionaries are a little quicker and a little less memory intensive than HashTables.
//This is because the kind "FIX" the type when we create the Dictionary - eg
//Dictionary<string, string> myDict = new Dictionary<string, string>();
static void Main()
{
//Syntax 1 for creating HashTable
Hashtable cities = new Hashtable();
cities.Add("UK", "London, Manchester, Preston");
cities.Add("USA", "Michigan, Las Vegas, Reno");
cities.Add("France", "Paris, Rennes, Le Mons");
//Building a string for showing
foreach(DictionaryEntry entry in cities)
{
Console.WriteLine(entry.Key + "=" + entry.Value);
}
//Syntax 2 for creating HashTable
Hashtable city = new Hashtable()
{
{ "UK", "London, Manchester, Preston" },
{ "USA", "Michigan, Las Vegas, Reno" },
{ "France", "Paris, Rennes, Le Mons" }
};
//String built using interpolation
foreach (DictionaryEntry entry in city)
{
Console.WriteLine("The key is {0}, the value is {1}", entry.Key, entry.Value);
}
//A dictionary drops straight into a Hashtable
Dictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("Honda", "CB300R, CB125F");
myDict.Add("Kawasaki", "Z250SL, Z400");
myDict.Add("Yamaha", "MT03, MT07");
Hashtable bikes = new Hashtable(myDict);
foreach(DictionaryEntry entry in bikes)
{
Console.WriteLine("Make {0}, Models {1}", entry.Key, entry.Value);
}
//Get one item
string qwe = bikes["Honda"].ToString();
Console.WriteLine(qwe);
//Update
bikes["Honda"] = "CB500X, CB750";
Console.WriteLine(bikes["Honda"].ToString());
//Remove
bikes.Remove("Yamaha");
foreach (DictionaryEntry entry in bikes)
{
Console.WriteLine("Make {0}, Models {1}", entry.Key, entry.Value);
}
//check it exists
if (bikes.ContainsKey("Honda"))
{
Console.WriteLine("We found Honda");
}
if (bikes.Contains("Honda"))
{
Console.WriteLine("We found Honda again");
}
//remove everything
bikes.Clear();
}
}
Reader's Comments
Fred said :-
Ta
04/12//2023 15:27:14 UTC
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home