I have a property that returns a HashTable
. I would like to sort it without refactoring my property. Please note: I do not want to return another type.
Code:
/// <summary>
/// All content containers.
/// </summary>
public Hashtable Containers
{
get
{
Hashtable tbl = new Hashtable();
foreach (Control ctrl in Form.Controls)
{
if (ctrl is PlaceHolder)
{
tbl.Add(ctrl.ID, ctrl);
}
// Also check for user controls with content placeholders.
else if (ctrl is UserControl)
{
foreach (Control ctrl2 in ctrl.Controls)
{
if (ctrl2 is PlaceHolder)
{
tbl.Add(ctrl2.ID, ctrl2);
}
}
}
}
return tbl;
}
}
Before moving forward, we need to understand that it is not possible to sort a Hashtable since the data is stored by the hashcode of the key, not by the index . So to sort the data of a Hashtable, we need to have a sortable object like an array or an ArrayList. Sorting has to be done on Key or Value.
A Hashtable has no predictable iteration order, and cannot be sorted. If you only want predictable iteration order you should use a LinkedHashMap . If you want to be able to sort your Map , you should use a TreeMap .
You have a hashtable of keys and values, and want to get the list of values that result from sorting the keys in order. To sort a hashtable, use the GetEnumerator() method on the hashtable to gain access to its individual elements. Then use the SortObject cmdlet to sort by Name or Value.
Hashtables are not sorted. So you need to make a copy of the hash table's key set, sort it, and retrieve the values from the hashtable by iterating through the keys in your sorted list. Or use a sorted hash table substitute, such as TreeMap; that would avoid having to make the copy of the key set.
Hashtables work by mapping keys to values. Implicit in this mapping is the concept that the keys aren't sorted or stored in any particular order.
However, you could take a look at SortedDictionary<K,V>
.
Another option is to construct the hash table as you're already doing, and then simply construct a sorted set from the keys. You can iterate through that sorted key set, fetching the corresponding value from the hash table as needed.
lubos is right: you can't sort a HashTable. If you could, it wouldn't be a HashTable. You can enumerate the HashTable, and then sort the enumeration. But that would be very slow. Much better to use a SortedDictionary
instead.
Sorry, but you can't sort hashtable. You will have to refactor your code to use some sortable collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With