Hashtable

S

SK

Hey,

i have a hashtable, where I am adding some values. Now
when I iterate through them then they start in reverse
order, why is that happening and how can I get rid of it?

Thanks
 
P

Peter Rilling

They do not necessarily reverse but a hashtable is not ordered so you are
not gaurenteed a specific list.
 
S

SK

Ok, here is my code:

Dim arParams As New Hashtable
arParams.Add("StartDate", txbStartDate.Text)
arParams.Add("EndDate", txbEndDate.Text)

Dim arEnum As IDictionaryEnumerator =
arParams.GetEnumerator()
While arEnum.MoveNext()
Response.Write(Convert.ToString(arEnum.Key) & "-" &
Convert.ToString(arEnum.Value) & "<br>")
End While

now it returns me first EndDate and then StartDate. If I
add then EndDate at first, then it still returns me first
EndDate. So can anybody tell me whats going on here?

Thanks
 
S

SK

Like this:

Dim arEnum As IDictionaryEnumerator =
arParams.GetEnumerator()
While arEnum.MoveNext()
Response.Write(Convert.ToString(arEnum.Key) & "-" &
Convert.ToString(arEnum.Value) & "<br>")
End While

Any idea?
 
P

Peter Rilling

It is simply the algorithm used for a hashtable. Hashtables by definition
are not ordered so you cannot expect them to be returned in the same order
as you entered them. This is simply a property of a hashtable.

What you could do is keep another ArrayList that keeps an ordered list of
all the keys so that if you need to cycle through them in a particular
order, then you would enumerate the keys, then use the key to access the
value from the hashtable.
 
S

SK

do you have an example on how I would get the values from
the hashtable via the arraylist?
 
S

SK

Isnt there any collection type which doesnt change its
order, but still works the way like adding "key" - "value"?
 
P

Peter Rilling

You can look at the System.Collection.Specialized namespace that might have
something that would work.
 
P

Peter Rilling

You would need to maintain your own ArrayList.

For example:

Dim arParams As New Hashtable
Dim alParamKeys As New ArrayList
arParams.Add("StartDate", txbStartDate.Text)
alParamKeys.Add("StartDate")
arParams.Add("EndDate", txbEndDate.Text)
alParamKeys.Add("EndData")

Dim arEnum As IEnumerator = alParamKeys.GetEnumerator()
While arEnum.MoveNext()
Response.Write(Convert.ToString(arParams.Item(arEnum.Value))
"<br>")
End While

This might not be exact syntax, but you get the idea.

Enumerate the array list (which has the keys). For each key, go into the
hashtable and get that value.
 

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

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top