Order Hastable by value

  • Thread starter Thread starter Guest
  • Start date Start date
Hello
I have a Hastable, which I need to order it by value and not by key.

Regards

Maybe I'm missing something, a hashtable is indexed by the key. What
difference does the ordering of the values do? :)
If you're trying to enumerate through the collection and require them to
arrive in a specific order then I'd suggest a Hashtable is not what you
want.

n!
 
n! said:
If you're trying to enumerate through the collection and require them to
arrive in a specific order then I'd suggest a Hashtable is not what you
want.


To elaborate a little more... perhaps you should make a class of two public
values: key and value:

public class KeyValPair
{
public object Key;
public object Val;
}

If you are frequently sorting/searching by value (and not key) then I would
probably use an ArrayList of KeyValPair for the entire app. You can make an
implementation of IComparer (something like below) to use with
ArrayList.Sort() for sorting by Val. You can also look into making your own
collection from CollectionBase or DictionaryBase.

public class ValueComparer : IComparer
int CompareValues (object x, object y)
{
KeyValPair xPair = x as KeyValPair;
KeyValPair yPair = y as KeyValPair;
// check for nulls, then compare xPair.Val and yPair.Val
return // the result
}

Or you can stick with your hashtable, and then when you want the sorted
values, loop through the Hashtable and add to the SortedList, possibly as
follows (although this seems really backwards to me):

SortedList list = new SortedList (hashtable.Count);
foreach (object key in hashtable.Keys)
{
list.Add (hashtable[key], key); // add the key-value pair as a value-key
pair - confusing...
}

How your app generally uses the collection and how much you want to optomize
for development time vs. performance will affect the method you should
probably take.
 
Back
Top