Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I thought that to clone a List you would just call:

List<int> cloneList = new List<int>(originalList);

But I tried that in my code and I seem to be getting effects that imply the above is simply doing:

cloneList = originalList... because changes to cloneList seem to be affecting originalList.

So what is the way to clone a List?

EDIT:

I am thinking of doing something like this:

public static List<T> Clone<T>(this List<T> originalList) where T : ICloneable
{
    return originalList.ConvertAll(x => (T) x.Clone());
}

EDIT2:

I took the deep copy code suggested by Binoj Antony and created this extension method:

public static T DeepCopy<T>(this T original) where T : class
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, original);
        memoryStream.Seek(0, SeekOrigin.Begin);
        return (T)binaryFormatter.Deserialize(memoryStream);
    }
}

EDIT3:

Now, say the items in the List are structs. What then would result if I called?:

List<StructType> cloneList = new List<StructType>(originalList);

I am pretty sure than I would get a List filled with new unique items, correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
110 views
Welcome To Ask or Share your Answers For Others

1 Answer

This would work...

List<Foo> cloneList = new List<Foo>(originalList);

When you say "because changes to cloneList seem to be affecting originalList." - do you mean changes to the list, or changes to the items...

Adding / removing / swapping items is changing the list - so if we do:

cloneList.Add(anotherItem);

you should find that cloneList is longer than originalList. However, if the contents are reference-types (classes), then both lists are still pointing at the same underlying objects - so if we do:

cloneList[0].SomeObjectProperty = 12345;

then this will also show against originalList[0].SomeObjectProperty - there is only a single object (shared between both lists).

If this is the problem, you will have to clone the objects in the list - and then you get into the whole deep vs shallow issue... is this the problem?

For a shallow copy, you might be able to use something very much like the answer here - simply with TTo = TFrom (perhaps simplify to a single T).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...