Search code examples
c#genericsclone

How to clone generic List<T> without being a reference?


I have a generic list of objects in C#, and wish to clone the list.

List<Student> listStudent1 = new List<Student>();
List<Student> listStudent2 = new List<Student>();

I used an extension method is below, but it can not : (when changes in listStudent2 -> affecting listStudent1)

public static List<T> CopyList<T>(this List<T> oldList)
{
    var newList = new List<T>(oldList.Capacity);
    newList.AddRange(oldList);

    return newList;
}

I would like to keep adding element or making changes in listStudent2 without affecting listStudent1. How do I do that?


Solution

  • You need to do a deep clone. That is to clone the Student objects as well. Otherwise you have two separate lists but both still point to the same students.

    You can use Linq within your CopyList method

    var newList = oldList.Select(o => 
                    new Student{
                                 id = o.id // Example
                                // Copy all relevant instance variables here
                                }).toList()
    

    What you might want to do is make your Student class be able to create a Clone of itself so you can simply use that in the select instead of creating a new student there.

    This would look something like:

    public Student Copy() {
            return new Student {id = this.id, name = this.name};
        }
    

    Within your student class.

    Then you would simply write

    var newList = oldList.Select(o => 
                    o.Copy()).toList();
    

    within your CopyList method.