How do I make HashTable sorted by value not key?

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#?
Who is Participating?
Göran AnderssonConnect With a Mentor 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

Guy Hengel [angelIII / a3]Billing EngineerCommented:
bind to a dataview (datatable) instead of a SortedList:

of course, you can create a datatable "on the fly", for example:
Sachintana DissanayakeConnect With a Mentor Senior Web DeveloperCommented:
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

All Courses

From novice to tech pro — start learning today.