Does LINQ return a deep copy of a collection?

Suppose I have a variable called PeopleCollection of type List<Person>

In the statement below, newPeople will get a deep copy of PeopleCollection?

 var newPeople=(from p in PeopleCollection select p).ToList(); 

Can any manipulation of newPeople affect PeopleCollection?

+6
source share
2 answers

This will create a new list and add all the items that were in this list to the new list. He will make a β€œshallow” copy of all these elements, so if these elements are mutable reference types that mutate them, they will be reflected from any collection.

This means that changes in any of the lists (adding elements, deleting elements, etc.) will not be displayed in another list, even if mutations for any element in the list are displayed from any collection.

(So, in a word, no, it won't.)

+10
source

It returns a List that references the same objects that were returned by Enumerable .

+3
source

All Articles