How to sort Hashtable by value and not key

  • Thread starter Thread starter max sharma
  • Start date Start date
M

max sharma

Hi all,
I am using hashtable in C# with keys of type string and values of type
double. I am not able to find a way to sort them by value (descending to
be precise) instead of key. Can someone please help me.
Thank you all in advance,
Max
 
max sharma said:
I am using hashtable in C# with keys of type string and values of type
double. I am not able to find a way to sort them by value (descending to
be precise) instead of key. Can someone please help me.
Thank you all in advance,

Use a second map, a SortedList, which stores the pairs the other way
round - so when you add an entry, you'd do something like:

normalMap[key] = value;
reverseMap[value] = key;
 
max said:
Hi all,
I am using hashtable in C# with keys of type string and values of type
double. I am not able to find a way to sort them by value (descending to
be precise) instead of key. Can someone please help me.

If you only need to sort once, something like:

string[] keys = new string[dict.Count];
dict.Keys.CopyTo(keys, 0);
double[] values = new double[dict.Count];
dict.Values.CopyTo(values, 0);
Array.Sort(values, keys);

If you need to access the data sorted by values while mutating the
hashtable you can implements your own datastructure which maintains: a
hash from string to double, and a sorted-list which maps the doubles to
strings. Be sure to delete the right values from the sorted-list if
duplicate doubles occur though.
 
Hi Max,

Did you check the Wintellect OrderedDictionary ? You can find the
code on www.wintellect.com under Power Collections for .Net. Don't
forget to create an account.

"Register here to get look at any stuff" -- Nah, I think I'll pass on that.
 
Thank you all for giving me such valuabe information...
I needed the solution quick so I did it on my own. I used a string[,]
array to store the key-value pairs and sorted this array based on values
using heap sort. It works and it pretty
fast considering the amount of data I have.
Thank you all once again.
Max
 
Thank you all for giving me such valuabe information...
I needed the solution quick so I did it on my own. I used a string[,]
array to store the key-value pairs and sorted this array based on values
using heap sort. It works and it pretty
fast considering the amount of data I have.
Thank you all once again.
Max
 

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

Back
Top