HashTable

  • Thread starter Thread starter web1110
  • Start date Start date
W

web1110

Hi y'all,

If I insert a set of keys and associated values in a HashTable, how do I
extract a given value for a specified key?

Thanx,
Bill
 
string myValue = (string)this.myHash[myKey];

....that is assuming, of course, that your value is a string. It can be
anything at all (in which case, replace the "string" definition and the
"(string)" cast with the correct type for your value).

You need the cast because Hashtable[] returns an Object in .NET v1.1,
so you have to cast the Object to the correct type for your value. In
..NET v2.0 you'll be able to create Hashtables that hold only particular
values, so you won't need the cast if you declare the hash table
properly. For now, though, you're stuck with having to cast.

If you ever need to iterate through all keys and values in a Hashtable,
you do that like this:

foreach (DictionaryEntry de in myHashtable)
{
string key = (string)de.Key;
string val = (string)de.Value;
... do something with key and val ...
}

Again, key can be any type and val can be any type... change the
definitions and the casts accordingly.
 
You can use ht.ContainsKey to see if key exists and the indexer ht[key]
to extract the value.
 
Back
Top