How do I clone a generic list in C#?

前端 未结 26 2996
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

26条回答
  •  猫巷女王i
    2020-11-22 02:12

    If your elements are value types, then you can just do:

    List newList = new List(oldList);
    

    However, if they are reference types and you want a deep copy (assuming your elements properly implement ICloneable), you could do something like this:

    List oldList = new List();
    List newList = new List(oldList.Count);
    
    oldList.ForEach((item) =>
        {
            newList.Add((ICloneable)item.Clone());
        });
    

    Obviously, replace ICloneable in the above generics and cast with whatever your element type is that implements ICloneable.

    If your element type doesn't support ICloneable but does have a copy-constructor, you could do this instead:

    List oldList = new List();
    List newList = new List(oldList.Count);
    
    oldList.ForEach((item)=>
        {
            newList.Add(new YourType(item));
        });
    

    Personally, I would avoid ICloneable because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method like YourType.CopyFrom(YourType itemToCopy) that returns a new instance of YourType.

    Any of these options could be wrapped by a method (extension or otherwise).

提交回复
热议问题