Hashtable

  • Thread starter Thread starter rk2008
  • Start date Start date
R

rk2008

I am using Hashtable to keep Key-Value pair of elements.
When I add the items to the Hashtable it does not retain the order in
which I have added the key-value pair.
Is there anyway to retain the order?
 
I am using Hashtable to keep Key-Value pair of elements.
When I add the items to the Hashtable it does not retain the order in
which I have added the key-value pair.
Is there anyway to retain the order?

Not using a HashTable. You would have to also add them to a collection
that does retain the order.
 
Howdy,

Hastable does not retain the order because items are oragnised by the key
hash code, allowing access in constant number of operations O(n). You would
have to create an additional list containing keys:

Hashtable hashtable =
new Hashtable();

List<string> history =
new List<string>();

for (int i = 0; i < 10; i++)
{
string key = Guid.NewGuid().ToString();

hashtable.Add(key, Guid.NewGuid());
history.Add(key);
}

// show how the items are organised in hashtable
foreach (DictionaryEntry pair in hashtable)
{
System.Diagnostics.Debug.WriteLine(
pair.Key.ToString() + "=" +
pair.Value.ToString());
}

System.Diagnostics.Debug.WriteLine(String.Empty);

// show items in order they were added
foreach (string key in history)
{
System.Diagnostics.Debug.WriteLine(
key + "=" +
hashtable[key].ToString());
}

Hope this helps

Milosz
 
Is there a collection that retains the order?

Most of them. I can only think of HashTable, Dictionary<> and
SortedList<> that doesn't.
 
The "Collection" object in the VB namespace does what you want, and there is
no equivalent currently built into C# or the .NET Framework.
But you can reference it and use it even if you're using C#.
 
Back
Top