Home >Backend Development >C++ >How to Create a True Deep Copy of a C# List?

How to Create a True Deep Copy of a C# List?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-11 18:47:43167browse

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 in C#, it is crucial to understand how to implement deep copy.

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, each element of the original list must be copied. This can be achieved using the following code:

<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’s ConvertAll method:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn