2016-11-25 23 views
-1

我有一個字典如何才能真正複製字典或列表數組?

Dim List4x As Dictionary(Of Byte, List(Of Byte)) = DuplicateDic(ByteList4) 

Public Shared Function DuplicateDic(ByVal List As Dictionary(Of Byte, List(Of Byte))) As Dictionary(Of Byte, List(Of Byte)) 
    Dim kv As New Dictionary(Of Byte, List(Of Byte)) 
    For Each itm As KeyValuePair(Of Byte, List(Of Byte)) In List 
     kv.Add(itm.Key, itm.Value) 
    Next 
    Return kv 
End Function 

如果我刪除舊錶我的新名單清算逐個項目..

如何才能真正複製一本字典或列表陣列?

感謝

+1

'List(Of T)'是一個引用類型(一個類)。您必須爲新詞典創建一個全新的列表。您可以像對待詞典一樣迭代每個列表,也可以製作[**深層複製**](http://stackoverflow.com/a/37085471/3740093)。 –

回答

2

你需要一個新的列表,否則兩個列表是相同的,如果你從列表中刪除2它,你也將從列表1中取出,因爲List(Of T)是引用類型。您可以使用this list constructor

Public Shared Function DublicateList(ByVal List As Dictionary(Of Byte, List(Of Byte))) As Dictionary(Of Byte, List(Of Byte)) 
    Dim kv As New Dictionary(Of Byte, List(Of Byte)) 
    For Each itm As KeyValuePair(Of Byte, List(Of Byte)) In List 
     Dim newList As New List(Of Byte)(itm.Value) ' <----- HERE !!! 
     kv.Add(itm.Key, newList) 
    Next 
    Return kv 
End Function 
+0

非常感謝。 –