How do I clone a generic list in C#?

前端 未结 26 2488
失恋的感觉
失恋的感觉 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条回答
  •  一生所求
    2020-11-22 02:08

    For a deep copy, ICloneable is the correct solution, but here's a similar approach to ICloneable using the constructor instead of the ICloneable interface.

    public class Student
    {
      public Student(Student student)
      {
        FirstName = student.FirstName;
        LastName = student.LastName;
      }
    
      public string FirstName { get; set; }
      public string LastName { get; set; }
    }
    
    // wherever you have the list
    List students;
    
    // and then where you want to make a copy
    List copy = students.Select(s => new Student(s)).ToList();
    

    you'll need the following library where you make the copy

    using System.Linq
    

    you could also use a for loop instead of System.Linq, but Linq makes it concise and clean. Likewise you could do as other answers have suggested and make extension methods, etc., but none of that is necessary.

提交回复
热议问题