Orders adding items to Hashtable.

G

Guest

I intended to save properties of an object to a Hashtable. In this case, keys and values are not fixed types and I cannot use SortedList.

I have no idea what order the .NET framework add items to Hashtable when Add(key, value) method is applied. Monitoring the position items are added, I cannot find if key is the standard or value.

I thought basically Hashtable function acts randomly, therefore the order will be changed unexpectedly.

However :

foreach (object o in objs)
{
CheckSomething(o, ref e81_o, ref l83_hn, ref l83_o, ref score);
Hashtable fields = o.Fields;
fields.Add("E81_O", e81_o);
fields.Add("L83_HN", l83_hn);
fields.Add("L83_O", l83_o);
fields.Add("Score", score);
}

In the case above, iteratively fields in all objs have the same order! For example, o.Fields has items originally in the order like,

H
V
S
E

and all objs have fields in the same order like below,

Score
L83_O
H
L83_HN
V
E81_O
S
E

But, extracting items in the reverse order like Stack.

Hashtable fields = new Hashtable();
foreach (object o in fields.Keys)
{
sb.Append(o.ToString() + " / " + fields[o].ToString());
}
 
J

Jon Skeet [C# MVP]

choyk1 said:
I intended to save properties of an object to a Hashtable. In this
case, keys and values are not fixed types and I cannot use
SortedList.

I have no idea what order the .NET framework add items to Hashtable
when Add(key, value) method is applied. Monitoring the position items
are added, I cannot find if key is the standard or value.

I'm not really sure of what your question is, but you shouldn't rely on
the order in which things come out of a hashtable. In some situations
it may *look* like it's ordered in a particular way, but that's likely
to be coincidence rather than anything else.
 

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

Top