HashTable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • web1110

    HashTable

    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


  • Bruce Wood

    #2
    Re: HashTable

    string myValue = (string)this.my Hash[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 (DictionaryEntr y de in myHashtable)
    {
    string key = (string)de.Key;
    string val = (string)de.Valu e;
    ... 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.

    Comment

    • Ajay Kalra

      #3
      Re: HashTable

      You can use ht.ContainsKey to see if key exists and the indexer ht[key]
      to extract the value.

      ------
      Ajay Kalra
      ajaykalra@yahoo .com

      Comment

      Working...