Hashtable

  • Thread starter Thread starter SK
  • Start date Start date
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
 
They do not necessarily reverse but a hashtable is not ordered so you are
not gaurenteed a specific list.
 
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
 
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?
 
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.
 
Isnt there any collection type which doesnt change its
order, but still works the way like adding "key" - "value"?
 
You can look at the System.Collection.Specialized namespace that might have
something that would work.
 
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.
 
Back
Top