-1

I am using VS2012, vb.net.

If I have a list of type t, and I wish to copy this to another list, the following code works:

list2.Clear()
list2.AddRange(list1)

However, if the first list of t has another list of type t2 inside it, this above code does not work.

Can I please have some help to copy the contents of a list of t to another list where the list of t has another list of t2 inside it.

Thanks

Garry
  • 1,251
  • 9
  • 25
  • 45
  • 1
    What exactly means `first list of t has another list of type t2 inside it`? Could you provide some working example code? Maybe you're looking for a deep copy of the list. – sloth Nov 29 '12 at 11:50
  • Agreed. I think your confusion comes from not understanding value types vs. reference types as well as shallow copying vs. deep copying. However, it's hard to say for sure without a clear example of what you mean. – Steven Doggart Nov 29 '12 at 12:49

1 Answers1

1
However, if the first list of t has another list of type t2 inside it, this above code does not work.

It does work, but it does a shallow copy, not a deep copy.

Let's say you want to do a deep copy of a List(Of List(Of Integer)). You can do it like this:

Dim list1 As List(Of List(Of Integer))

*Populate list 1*

Dim copy = list1.Select(Function(innerList) innerList.ToList).ToList

Now you have to independent lists, because you copy each inner list with ToList, and also copy the outer list with ToList. Note that if you had reference type objects instead of integers in the inner list, you would also need to clone each individual object to do a deep copy.

Community
  • 1
  • 1
Meta-Knight
  • 17,626
  • 1
  • 48
  • 58