Adham
Adham

Reputation: 64904

How to add List as value in Hashtable

In vb.net If I have HashTable,key is integer and the value is a list of integers, how to append integers to the value of a given key, I have tried it but each time I found the integer last added only, (the list only has the last item added).

Here is my code , where dt is DataTable object

Dim dt = report.getEvaluationReportByObjectiveGroupId(29)
Dim data As New Hashtable()
Dim dataEntry As DictionaryEntry

Dim res As String
For Each row As DataRow In dt.Rows
    Dim strYear = row.Item("Year")
    Dim strData = row.Item("EmpCount")


    If data.ContainsKey(strYear) Then
        Dim newCountArr As List(Of Int32) = DirectCast(data(strYear), List(Of Int32))
        '   newCountArr.AddRange(data(strYear))
        newCountArr.Add(strData)
        '  data.Remove(strYear)
        ' data.Add(strYear, newCountArr)
    Else
        Dim countArr As New List(Of Integer)
        countArr.Add(strData)
        data.Add(strYear, countArr)
    End If

    ' data.Add(strYear, strData)
Next row

Upvotes: 0

Views: 3730

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460228

I would suggest to use the strongly typed Dictionary(Of Int32, List(Of Int32)) instead, it works similar. But anyway, here's the HashTable approach:

Dim table = New Hashtable
Dim list = New List(Of Int32)
For i = 1 To 999
    list.Add(i)
Next
table.Add(1, list)

' somewhere else you want to read the list for a given key (here 1) '
Dim list1 As List(Of Int32) = DirectCast(table(1), List(Of Int32))
list.Add(1000) ' add another integer to the end of the list '
' note: you don't need to add the list to the HashTable again '

Edit: Since you've posted your code, here's the corrected:

For Each row As DataRow In dt.Rows
    Dim strYear = row.Field(Of Int32)("Year")
    Dim strData = row.Field(Of Int32)("EmpCount")
    Dim list As List(Of Int32)

    If data.ContainsKey(strYear) Then
        list = DirectCast(data(strYear), List(Of Int32))
    Else
        list = New List(Of Int32)
        data.Add(strYear, list)
    End If
    list.Add(strData)
Next row

Upvotes: 1

Related Questions