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

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

Patricia Arquette
Release: 2025-01-11 18:36:42
Original
469 people have browsed it

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

Deep Copying Lists in C#

Directly assigning a list in C# (e.g., List<T> list2 = list1;) or using List<T> list2 = new List<T>(list1); creates a shallow copy. Modifications to one list affect the other because they share the same underlying objects. To create a true deep copy, where changes to one list are independent of the other, you need to duplicate the contained objects. Here's how:

Method 1: Using LINQ (Recommended)

The most concise and efficient approach utilizes LINQ's Select method to create new instances of each object within the list:

<code class="language-csharp">List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();</code>
Copy after login

This line iterates through books_1, creates a new Book object for each element using the existing title (assuming your Book class has a constructor that takes the title), and then converts the resulting sequence back into a new List<Book>.

Method 2: Using ConvertAll (Alternative)

The ConvertAll method offers a slightly simpler syntax for the same outcome:

<code class="language-csharp">List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));</code>
Copy after login

This achieves the same deep copy as the LINQ approach. Choose whichever method you find more readable.

Both methods ensure that books_2 is a completely independent deep copy of books_1. Any changes made to either list will not affect the other. Remember that this assumes your Book class (or whatever type your list contains) has a suitable constructor to facilitate the creation of new instances. If your Book class has more properties, you'll need to include them in the new Book(...) constructor call accordingly.

The above is the detailed content of How to Create a Deep Copy of a List in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template