Home >Backend Development >C++ >How to Create a True Deep Copy of a C# List?
A true deep copy method for creating List
Introduction
In many programming scenarios, it is crucial to create a truly independent copy of the original data structure. For List
Question
Consider the following code snippet:
<code class="language-csharp">List<Book> books_1 = new List<Book>(); books_1.Add(new Book("One")); books_1.Add(new Book("Two")); books_1.Add(new Book("Three")); books_1.Add(new Book("Four")); List<Book> books_2 = new List<Book>(books_1); books_2[0].title = "Five"; books_2[1].title = "Six"; // 对books_2的更改会反映在books_1中 textBox1.Text = books_1[0].title; textBox2.Text = books_1[1].title;</code>
Although this code creates a new list, the Book object in books_2 is still a reference to the same object in books_1. Therefore, modifications to books_2 will affect books_1.
Solution
To create a true deep copy of List
<code class="language-csharp">List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();</code>
Each Book object in books_1 is converted into a new Book object by using LINQ's Select method. These new objects are then stored in books_2, resulting in a deep copy.
Alternatively, you can take a simpler approach using List
<code class="language-csharp">List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));</code>
This method returns a new list where each element is the result of transforming the corresponding element in the original list.
With this approach, books_2 and books_1 are independent of each other, and changes to one list will not affect the other.
The above is the detailed content of How to Create a True Deep Copy of a C# List?. For more information, please follow other related articles on the PHP Chinese website!