how to make a deep copy of my list

后端 未结 2 1564
我寻月下人不归
我寻月下人不归 2020-12-21 11:46
 Dim i = 2
    Do While True
        i += 1
        If IsDBNull(TmDataSet.T.Rows(0)(i)) = True Then Exit Do
        Dim new_t As New train
        new_t.id = TmDataS         


        
相关标签:
2条回答
  • 2020-12-21 11:53

    You can create an extension method where you serialize the object only to deserialize it again. This will create a new object with it's own references, thus a Deep Copy.

    Public Module Extensions
        <System.Runtime.CompilerServices.Extension()> _
        Public Function DeepCopy(Of T)(ByVal Obj As T) As T
            If Obj.GetType().IsSerializable = False Then Return Nothing
    
            Using MStream As New MemoryStream
                Dim Formatter As New BinaryFormatter
                Formatter.Serialize(MStream, Obj)
                MStream.Position = 0
                Return DirectCast(Formatter.Deserialize(MStream), T)
            End Using
        End Function
    End Module
    

    Now you can just call:

    Dim network As List(Of train) = per_network.DeepCopy()
    

    EDIT:

    These are the required imports for my code above:

    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary
    
    0 讨论(0)
  • 2020-12-21 12:01

    This is the code I used

    Dim deepCopies = _dictOfBalances1.Keys.ToList
    

    Basically deepCopies is a deep copy of _dictOfBalances1.Keys

    This code won't work if deepCopies are shallow copies.

    For Each code In deepCopies
        If allthecoincode.Contains(code) Then
        Else
            _dictOfBalances1.Remove(code)
            'deletedKeys.Add(code)
        End If
    Next
    
    0 讨论(0)
提交回复
热议问题