2012-09-17 93 views
0

列表中添加的價值在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

我會建議使用強類型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 
+0

請檢查我的代碼,每個最後一個值是在時間名單,我不知道爲什麼? – Adham

+0

@Adham:我編輯了我的答案。 –

+0

Thnaks但什麼是新的?我仍然只有數據表中最後一行的值! – Adham