【问题标题】:How to add List as value in Hashtable如何将列表添加为哈希表中的值
【发布时间】:2012-09-17 09:07:15
【问题描述】:

在 vb.net 如果我有HashTable,key 是整数并且值是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

【问题讨论】:

    标签: vb.net list hashtable


    【解决方案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
    

    【讨论】:

    • 请检查我的代码,每次最后一个值都在列表中,我不知道为什么?
    • Thnaks 但有什么新功能?我仍然只有数据表中最后一行的值!
    • 您是否使用调试器检查过这些值并查看它是否输入了ContainsKey
    • 是的确实输入 ContainsKey :)
    • 新的是(除其他外)我使用整数而不是对象。 EqualsGethashCodeObject 只比较相同的引用而不是相等的值。
    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2018-12-28
    相关资源
    最近更新 更多