469,628 Members | 1,044 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,628 developers. It's quick & easy.

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
Nov 16 '05 #1
2 13583
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.

Nov 16 '05 #2
You can use ht.ContainsKey to see if key exists and the indexer ht[key]
to extract the value.

------
Ajay Kalra
aj*******@yahoo.com

Nov 16 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by francois | last post: by
8 posts views Thread by SenthilVel | last post: by
33 posts views Thread by Ken | last post: by
16 posts views Thread by Sreekanth | last post: by
3 posts views Thread by Fred | last post: by
8 posts views Thread by Robin Tucker | last post: by
7 posts views Thread by SevDer | last post: by
2 posts views Thread by archana | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.