Created
April 30, 2012 09:13
-
-
Save AndrewBarfield/2556751 to your computer and use it in GitHub Desktop.
C#: System.Collections.Hashtable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
namespace HashtableExample { | |
class Program { | |
static void Main(string[] args) { | |
// Create a new hashtable | |
Hashtable genericDomains = new Hashtable(); | |
// Add values to the hashtable | |
genericDomains.Add( "com", "Commercial Organizations" ); | |
genericDomains.Add( "net", "Network Infrastructures" ); | |
genericDomains.Add( "org", "Organization" ); | |
genericDomains.Add( "gov", "U.S. Government" ); | |
// Access values by the default Item property | |
Console.WriteLine( "For key \"com\" the value is \"{0}\".", genericDomains["com"] ); | |
Console.WriteLine( "For key \"org\" the value is \"{0}\".", genericDomains["org"] ); | |
// Change a value by the default Item property | |
genericDomains["com"] = "Commercial Organizations, but unrestricted"; | |
Console.WriteLine( "For key \"com\" the value is \"{0}\".", genericDomains["com"] ); | |
// Add a new key/value pair | |
genericDomains["edu"] = "Post-Secondary Educational Establishments"; | |
// Use ContainsKey to test keys before inserting them | |
if ( !genericDomains.ContainsKey( "mil" ) ) { | |
genericDomains.Add( "mil", "U.S. Military" ); | |
Console.WriteLine( "Value added for key = \"mil\": {0}", genericDomains["mil"] ); | |
} | |
// Enumerate hashtable KeyValuePair objects | |
Console.WriteLine(); | |
foreach ( DictionaryEntry de in genericDomains ) { | |
Console.WriteLine( "Key = {0}, Value = {1}", de.Key, de.Value ); | |
} | |
// Use the Values property to get just the values | |
ICollection valueColl = genericDomains.Values; | |
Console.WriteLine(); | |
foreach ( string s in valueColl ) { | |
Console.WriteLine( "Value = {0}", s ); | |
} | |
// Use the Keys property to get just the keys | |
ICollection keyColl = genericDomains.Keys; | |
Console.WriteLine(); | |
foreach ( string s in keyColl ) { | |
Console.WriteLine( "Key = {0}", s ); | |
} | |
// Use the Remove method to remove a key/value pair | |
Console.WriteLine( "\nRemove(\"net\")" ); | |
genericDomains.Remove( "net" ); | |
// Test the keys for the removed key | |
if ( !genericDomains.ContainsKey( "net" ) ) { | |
Console.WriteLine( "Key \"net\" is not found." ); | |
} | |
Console.Read(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment