Shared lists copying links, not creating a copied list

I developed a small function when trying to start an enumerator on a list and then perform some action. (Below is the idea of ​​what I was trying to do.

When I tried to delete, I got "Collection cannot be changed", which, after I really woke up, realized that tempList should just be assigned as a link to myLists, and not a copy of myLists. After that I tried to find a way to say

tempList = myList.copy

However, nothing similar exists ?? I ended up writing a little loop, which then added only every element from myLsit to tempList, but I would have thought there would be another mechanism (e.g. clone?)

So my question (s):

  • - my assumption is that tempList gets the link to myList correctly.
  • How should a list be copied to another list?

        private myList as List (Of something)
    
    sub new()
        myList.add(new Something)
    end sub
    
    sub myCalledFunction()
        dim tempList as new List (Of Something)
        tempList = myList
        Using i as IEnumerator = myList.getEnumarator
           while i.moveNext
               'if some critria is met then 
               tempList.remove(i.current)
           end
        end using
    
    end sub
    
+3
source share
4 answers

We write tempList = myList, you do not make a copy of the collection, you only make the link temlList myList. Try instead:dim tempList as new List (Of Something)(myList)

+8
source

Try this - use LINQ to create a new list from the original, for example:

Sub Main()
        Dim nums As New List(Of Integer)

        nums.Add(1)
        nums.Add(2)
        nums.Add(3)
        nums.Add(4)

        Dim k = (From i In nums _
                 Select i).ToList()

    For Each number As Integer In nums
        k.Remove(number)
    Next
    End Sub

k will then be a new list of numbers that are not related to the source.

0
source

, myCalledFunction (byVal aListCopy -), .

0

If your list consists of value types, you can simply create a new list with the old list passed in the constructor. If you are going to make a deep copy of the reference object, it is best to use your reference type ICloneable( example ), then you can scroll and clone each object, or you can add an extension method (for example, this C # example ).

0
source

Source: https://habr.com/ru/post/1735926/


All Articles