See the example here, i stored values in this order! But the output i'm getting is different! Why? In what order the Hashtable Storing the Values?
{
Hashtable ht = new Hashtable();
ht.Add("001", "Zara Ali");
ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");
ht.Add("005", "M. Amlan");
ht.Add("006", "M. Arif");
ht.Add("007", "Ritesh Saikia");
ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}
}
Ouput
006: M. Arif
007: Ritesh Saikia
003: Joe Holzner
002: Abida Rehman
004: Mausam Benazir Nur
001: Zara Ali
005: M. Amlan
A Hashtable does not guarantee any defined order to the elements within. The implementation of the hashtable splits the values into different buckets based on their Hashcode and its internal implementation, meaning the same values could have different order on different machines, different runs or different versions of the framework. This is because Hashtables are optimized for by-key-retrieval, rather than by-order retrieval.
If you want a collection that can be accessed both by key and in-order, use one of the specialized collections. Judging by your use of
Hashtable
rather thanDictionary<K,V>
, it's possible you're using .NET 1.1, in which case you can useSortedList
which will maintain order internally. Newer versions of .NET haveSortedList<K,V>
andOrderedDictionary<K,V>
which differ a bit in their performance characteristics: