Print out contents of a hashtable

  • Thread starter Water Cooler v2
  • Start date
W

Water Cooler v2

I can't believe I've stumbled on a simple problem such as this. After
all these years, that too.

Anyway, it goes that I just realized that I could not iterate through
my hashtable and print out its contents. On further probing, I realized
that the hashtable didn't implenent IList, which really has the
this[int] indexer. And so I couldnt do this:

for (int i = 0; i < _myHashTable.Count; i++)
Console.WriteLine(_myHashTable.ToString());

I had to know the key to index the hashtable elements. I could
enumerate through it by getting its enumerator
(IEnumerable.GetEnumerator) and then calling Next() and Current on its
IEnumerator but even then, I'd have to know the keys.

I took the hashtable in the first place because of its Contains method.
It can easily reference its elements and check for the existence of a
key, in constant time whereas list takes linear time.

Now, I am stuck. All I need to do is print out the contents of the
hashtable. The other option I can consider is to take a Dictionary or a
NameValueCollection or to take an ArrayList and extend it to have a
Contains look up method.
 
W

Water Cooler v2

People, never mind, I am using a System.Collections.SortedList. It's
got what I need.

bool Contains(key);
object GetKey(int);

And I don't mind if the items are all sorted.
 
G

Guest

Water Cooler v2,

Think of the hashtable as a collection of DictionaryEntry objects, with your
custom object stored in the DictionaryEntry's Value property.

Use a For Each loop to iterate through the hashtable and cast your object
from DictionaryEntry.Value:

For Each de As DictionaryEntry in myHashTable
myObject = DirectCast (de.Value, myClass)
Next

Kerry Moorman
 
T

Truong Hong Thi

To iterate:
foreach (DictionaryEntry entry in t)
{
Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
}

If you want to check if the hash table contains a key/value, try using
ContainKey (same as Contains, but method name makes it clearer) and
ContainsValue methods.
 
W

Water Cooler v2

Oh yeah! Thanks, Kerry and Truong. I was wondering how I could cast the
"object" inside the hashtable into an object that looked like a
dictionaryentry. Only, I didn't see the obvious.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top