"Sorting" a hashtable

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

I have a hashtable (h) of class objects keyed by a string (k) - the class
(c) object stored in each hastable entry has two attributes (a1 and a2).

I want to iterate through the entries of the hashtable by ordering by one of
the attributes of the class (a1 or a2).

How can this easily be achieved ? I think I have to copy to an ArrayList
then write an IComparer - but I'm not sure if this is the best way.

Any advice appreciated.
 
You can instantiate the ArrayList from the Keys property of the hashtable.
Then sort the ArrayList (no need to write a comparer). You can then iterate
through the keys in the arraylist and lookup the associated value in the
hashtable.

If you don't want that final step (coz of performance), you could write a
comparer for the object (assuming the key is also stored in the object),
instantiate the ArrayList from the Values property, and then sort using your
custom comparer. The ArrayList will then contain a sorted list of your
objects.
 
Won't that just order by the hashtable key ? I want to order by an attribute
in the hashtable values.
 
Ah, now that I've read your question properly...... ;)
Yeah sorry about that. So the attribute has some kind of parameter that
would become the sort key?
I think you will need to write a custom comparer, as the only way to get
hold of the attributes is through the type.
 
That's what I ended up having to do.

John Wood said:
Ah, now that I've read your question properly...... ;)
Yeah sorry about that. So the attribute has some kind of parameter that
would become the sort key?
I think you will need to write a custom comparer, as the only way to get
hold of the attributes is through the type.

write
 
Back
Top