如何在Hashtable中将List添加为值

时间:2012-09-17 09:07:16

标签: vb.net list hashtable

在vb.net中如果我有HashTablekey是整数,值是list of integers,那么如何将整数附加到给定键的值, 我试过了,但每次我发现最后一次添加的整数,(列表只添加了最后一项)。

以下是我的代码,其中dtDataTable对象

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

1 个答案:

答案 0 :(得分:1)

我建议使用强类型Dictionary(Of Int32, List(Of Int32)),它的工作方式类似。但无论如何,这是HashTable方法:

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 '

修改:由于您已发布代码,因此更正了以下内容:

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