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#?
bemara57Asked:
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

0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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
0
 
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

0
All Courses

From novice to tech pro — start learning today.