Easy way to copy a List<List<T>>

  • Thread starter Thread starter Sin Jeong-hun
  • Start date Start date
S

Sin Jeong-hun

List<List<T>> a=param;
List<List<T>> b=a;
If I change b, then a is get changed. I want another copy of a, that is
completely independent of a. I used double-nested for loop to copy each
element manually. Is there any more efficent way to do that? Something
like,
List<List<T>> b=CreateClone(a);

Thanks.
 
Sin Jeong-hun,

The easiest way to do this would be to use the ConvertAll method on the
instance itself. You can always convert the list to itself. =)

So, you can do:

// This assumes T is a valid type.
List<List<T>> a = param;

// Make a copy.
List<List<T>> b = a.ConvertAll(delegate(T input) { return input; });

Basically, you are passing the value through to a new list.

Hope this helps.
 
Thank you all!
Sin Jeong-hun,

The easiest way to do this would be to use the ConvertAll method on the
instance itself. You can always convert the list to itself. =)

So, you can do:

// This assumes T is a valid type.
List<List<T>> a = param;

// Make a copy.
List<List<T>> b = a.ConvertAll(delegate(T input) { return input; });

Basically, you are passing the value through to a new list.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Sin Jeong-hun said:
List<List<T>> a=param;
List<List<T>> b=a;
If I change b, then a is get changed. I want another copy of a, that is
completely independent of a. I used double-nested for loop to copy each
element manually. Is there any more efficent way to do that? Something
like,
List<List<T>> b=CreateClone(a);

Thanks.
 
Nicholas Paldino said:
// Make a copy.
List<List<T>> b = a.ConvertAll(delegate(T input) { return input; });

This won't compile - you need to write "ConvertAll<List<T>>". More
importantly, this only clones the 'outer list' - you get a new list of
the same inner List<T> elements. If you want a wholly independent copy
(so that changing one of the lists in the original tree doesn't affect
the copy) you need

List<List<T>> DeepCopy =
List.ConvertAll<List<T>>(delegate(List<T> Branch)
{
return Branch.ConvertAll<T>(delegate(T Leaf){return Leaf;});
});
 
List said:
List.ConvertAll<List<T>>(delegate(List<T> Branch)
{
return Branch.ConvertAll<T>(delegate(T Leaf){return Leaf;});
});

If T is a reference type, this method will still not be "deep" enough.
The leafs will just be refering to the same objects. To fix this I
guess you could make sure T inmplementes ICloneable and let Clone()
return a deap copy of T. Then the code should be:

List<List<T>> DeepCopy =
List.ConvertAll<List<T>>(delegate(List<T> Branch)
{
return Branch.ConvertAll<T>(delegate(T Leaf){return
Leaf.Clone();});
});
 
Back
Top