We help IT Professionals succeed at work.

How do I make HashTable sorted by value not key?

bemara57
bemara57 asked
on
I want to return a list of key/value pairs which I'm binding to a drop down. But I want it to be sorted by value, not key. I tried to use a SortedList, but that obviously sorts by key. How can I achieve this in C#?
Comment
Watch Question

Guy Hengel [angelIII / a3]Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
bind to a dataview (datatable) instead of a SortedList:
http://en.csharp-online.net/DataViews_and_Data_Binding%E2%80%94Sorting_with_the_DataView

of course, you can create a datatable "on the fly", for example:
http://www.tanguay.info/web/codeExample.php?id=377
Sachintana DissanayakeSenior Web Developer
CERTIFIED EXPERT
Commented:
Use a string[] and double[] to copy keys and values to two separate arrays.
Then use Array.Sort() method to sort by values.
See the sample code here...

//Existing hash table to be sorted.
Hashtable hash = new Hashtable();
 
string[] keys = new string[hash.Count];
double[] values = new double[hash.Count];
 
hash.Keys.CopyTo(keys, 0);
hash.Values.CopyTo(values, 0);
Array.Sort(values, keys);

Open in new window

CERTIFIED EXPERT
Commented:
You can use a custom comparer to sort a List on anything you like:
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("1", "Last"));
list.Add(new KeyValuePair<string, string>("2", "First"));
list.Add(new KeyValuePair<string, string>("3", "Inbetween"));
list.Sort(delegate(KeyValuePair<string, string> x, KeyValuePair<string, string> y) { return string.Compare(x.Value, y.Value); });

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.