Güven Acar Güven Acar - 8 days ago 6
Vb.net Question

How can keep my list values after duplicate?

I have a Dictionary

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


Public Shared Function DuplicateList(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 duplicate list and clear old list not deleting items in my duplicated list (List4x)

ByteList4.Clear()

List4x items are keeping

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

Public Shared Function GrupCoz(ByVal ByteList As List(Of Byte), ByVal Mat As Dictionary(Of Byte, List(Of Byte)), ByVal Gruplar As Dictionary(Of Byte, List(Of Byte))) As List(Of Byte)
Dim ByteList2 As New List(Of Byte)
Dim GrupNo, GrupSiraNo As Byte
For i As Integer = 0 To ByteList.Count - 1
GrupNo = ByteList(i)
GrupSiraNo = Mat(GrupNo)(0)
ByteList2.Add(Gruplar(GrupNo)(GrupSiraNo))
Mat(ByteList(i)).RemoveAt(0)
Next
Return ByteList2
End Function


List4x items removing after this.
How can i keep my list items after remove? 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