By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,919 Members | 1,867 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,919 IT Pros & Developers. It's quick & easy.

Order Hastable by value

P: n/a
Hello
I have a Hastable, which I need to order it by value and not by key.

Regards
Nov 15 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
n!
> 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!
Nov 15 '05 #2

P: n/a
"n!" <nf********@nomailplease.com> wrote in message
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.

--
Mike Mayer - Visual C# MVP
http://www.mag37.com/csharp/
mi**@mag37.com


Nov 15 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.