C#: Sorting A Hashtable By Values (not Keys)
{ Posted on Nov 09 2009 by Sherri }
Outputting a C# Hashtable in sorted order by the keys is easy enough. Copy the keys to an array, sort that array, then iterate through the sorted keys to output the Hashtable values. But what if you want the Hashtable sorted by value. For example if your hashtable has a username as the key and the Lastname, First as the value?
Well, after much searching I figured it out myself. Here you go:
/* Get the keys of a HashTable in alphabetical order according to the Values. */
private string[] getKeysInValueOrder(Hashtable arrayToSort)
{
string[] keys = new string[arrayToSort.Count];
arrayToSort.Keys.CopyTo(keys, 0);
Array.Sort(keys, delegate(string x, string y){
return (arrayToSort[x].ToString() as IComparable).CompareTo(arrayToSort[y].ToString());
}
);
return keys;
}

Sherri Wheeler is a web developer and business professional in Windsor, Ontario. She manages several websites and specializes in web development. | 