Is there a way to sort a hashtable?

  • Thread starter Thread starter Arjen
  • Start date Start date
A

Arjen

Hello,

Let's say that we have a hashtable with some person objects.
This persons have a name.

Now I want to sort the people objects inside the hashtable by name.
How can the hashtable do this for me?

Thanks!
 
Arjen said:
Let's say that we have a hashtable with some person objects.
This persons have a name.

Now I want to sort the people objects inside the hashtable by name.
How can the hashtable do this for me?

You can't - a hashtable is effectively a set, not a sequence: it
doesn't have an order.

What you *can* do is:

ArrayList al = new ArrayList (hashtable.Values);
al.Sort (myNameComparator);
 
Alternatively, there is the SortedList class which is a hybrid between
the Hashtable and ArrayList. (it sorts based on the key)

Although, it sounds as if your Hashtable stores the Person objects as
the value in which case this wouldn't work.

Nonetheless, now you know there's a SortedList. :)
 
Hi Arjen,
As long as hashtables are not ordered collections you cannot sort them.
However, you can maintain a separate list along with the hashtable which
will keep the order of the elements and you can sort this list and use it
latter to retreive the elements.
Take a look on System.Collections.SortedList as well. It might be exactly
what you are after.

HTH
B\rgds
100
 
Back
Top