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