Hashtable

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?
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 
G

Guest

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Is there a collection that retains the order?

Most of them. I can only think of HashTable, Dictionary<> and
SortedList<> that doesn't.
 
S

Steve C. Orr [MCSD, MVP, CSM, ASP Insider]

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#.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top