By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,645 Members | 1,048 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,645 IT Pros & Developers. It's quick & easy.

HashTable

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.