Sort HashTable by Key

M

Mark

I'm using an enumerator to iterate through a HashTable that contains all
numeric keys. I'd like to iterarate through the HashTable based on the
ordered keys. Is there a quick way to do this? Thanks! -Mark

IDictionaryEnumerator myEnumerator = myHashTable.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
//Please print ordered by Key ...
Response.Write("<BR>" + myEnumerator.Key.ToString() + ", " +
myEnumerator.Value.ToString())
}
 
M

Michael Lang

I'm using an enumerator to iterate through a HashTable that contains
all numeric keys. I'd like to iterarate through the HashTable based
on the ordered keys. Is there a quick way to do this? Thanks! -Mark

IDictionaryEnumerator myEnumerator = myHashTable.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
//Please print ordered by Key ...
Response.Write("<BR>" + myEnumerator.Key.ToString() + ", " +
myEnumerator.Value.ToString())
}

You cannot sort a hashtable. data is not stored in an ordered fashon.

from help:
"When an element is added to the Hashtable, the element is placed into a
bucket based on the hash code of the key. Subsequent lookups of the key
use the hash code of the key to search in only one particular bucket,
thus substantially reducing the number of key comparisons required to
find an element."

values property:
"The order of the values in the ICollection is unspecified, but it is
the same order as the associated keys in the ICollection returned by the
Keys method."

This is why hashTable is faster for key based storage. If you are using
only index based indexers then use an ArrayList or other index based
collection. The ArrayList has a Sort method. The SortedList is always
sorted.

If you require both index and key based indexers then you need to create
your own hybrid collection type. I recommend you derive from
CollectionBase and then add an internal HashTable for storing by key.
CollectionBase already contains an internal ArrayList for storing by
index.

I've just created a sample collections demo project. I was planning on
writing a generator today to create a strongly typed collection of any
type that is accessed by index or key. I will put it on sourceforge.
I'll post a reply to this message when it is complete and available for
download with a link.
 

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