Güven Acar Güven Acar - 7 days ago 7
Vb.net Question

How can real duplicate a dictionary or a list array?

I have a Dictionary

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


If i remove one by one items in old list my new list clearing..

How can real duplicate a dictionary or a list array?

Thanks

Answer

You need a new list, otherwise both lists are same and if you remove it from list 2 you will also remove it from list 1 because List(Of T) is a reference type. You can use 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
Comments