Hashtable items order

  • Thread starter Thread starter Nadav
  • Start date Start date
N

Nadav

Hello.
I have a Hashtable, to which I insert key and values.
When I go over the hashtable with "foreach" later on,
the items are not coming out at the order I inserted them.
A quickwatch showed that as the items are inserted, they are not arranged in
the hash at the order they were inserted by.

Is there a way to control that with a hashtable ? I can't even sort it...
Thanks
 
Nadav said:
I have a Hashtable, to which I insert key and values.
When I go over the hashtable with "foreach" later on,
the items are not coming out at the order I inserted them.

No, they wouldn't (necessarily).
A quickwatch showed that as the items are inserted, they are not arranged in
the hash at the order they were inserted by.

Is there a way to control that with a hashtable ? I can't even sort it...

Hashtables aren't inherently ordered - they're maps. You could use
SortedList (which is actually a map, despite the name, sorted by key),
but if you want insertion order, it's probably easiest to keep a
parallel ArrayList.
 
AFAIK no.

You can create wrapper that will consist of hashtable for fast search and a
list for iteration.
That is when you do myCustHashtable[key] - intrnal hashtable is involved,
and when you do foreach(Key k in myCustHashtable.Keys) - list is involved.

With this approach you have to keep internal hastable and list in
synchronized state.
 
Hello Nadav,

Look at System.Collections.Specialized.NameObjectCollectionBase (ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref2/html/T_System_Collections_Specialized_NameObjectCollectionBase.htm)

There is an example how to build smth like Hashlist - to keep keys/values
and get them by order

It should helps

N> I have a Hashtable, to which I insert key and values.
N> When I go over the hashtable with "foreach" later on,
N> the items are not coming out at the order I inserted them.
N> A quickwatch showed that as the items are inserted, they are not
N> arranged in
N> the hash at the order they were inserted by.
N> Is there a way to control that with a hashtable ? I can't even sort
N> it... Thanks
N>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/members/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsch
 
If you insist on using a Hashtable (which you might, because insertion
speed is a lot faster than for SortedList), the only way you can sort
is to do a ToArray() and then sort the resulting array on demand.

However, as Jon pointed out, there is SortedList, which is probably
what you want.
 

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

Back
Top