Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

clone

generics

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?

like image 916
MinhKiyo Avatar asked Nov 01 '25 23:11

MinhKiyo


1 Answers

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.

like image 190
Johan Gronberg Avatar answered Nov 04 '25 13:11

Johan Gronberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!