Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ return a deep copy of a collection?

Tags:

c#

linq

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

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

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

Could any manipulation to newPeople affect PeopleCollection ?

like image 858
developer747 Avatar asked Apr 22 '13 19:04

developer747


2 Answers

That will create a new list and add all of the items that were in that list to the new list. It will perform a "shallow" copy of all of those items, so if those items are mutable reference types mutating them will be reflected from either collection.

This means that changes to either list itself (adding items, removing items, etc.) won't be reflected in the other list, even though mutations to any item in the list will be reflected from either collection.

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

like image 166
Servy Avatar answered Sep 30 '22 12:09

Servy


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

like image 40
w.brian Avatar answered Sep 30 '22 12:09

w.brian