6

Does LINQ actually perform a deep copy of the results to a different list/array/etc, or does it simply give me a list/array/etc. composed of references to the original?

4

3 回答 3

10

It's going to depend on if (and how) you use Select to project the results.

If you do not create new objects in a projection then the result will reference the same objects as the original collection.

If, however, you create new objects in the project then, obviously, they will not be the same.

The collection returned here will contain references to the same objects in _myCollection:

from m in _myCollection
where m.SomeFilterCriteria
select m

The collections returned in these cases will not:

from m in _myCollection
where m.SomeFilterCriteria
select new { m.Prop1, m.Prop2 }

In this case, it is worth pointing out that Prop1 and Prop2 of the new anonymous object - if they are reference types - will contain a reference to the same object as the original object. Only the top-level references in the collection will be different.

Basically - nothing in .Net aside from serializers (as mentioned elsewhere here) will "deep" copy, unless you implement it.

or

from m in _myCollection
where m.SomeFilterCriteria
select m.Clone()

Again, it would be a mistake to assume that any "deep" copying is going on here. Of course, Clone's implementation will be in the class and could be anything, including deep copying, but that is not given.

于 2011-01-21T18:41:17.983 回答
3

Does LINQ actually perform a deep copy of the results to a different list/array/etc, or does it simply give me a list/array/etc. composed of references to the original?

From Enumerable.ToArray. (Similiar text found at Enumerable.ToList)

The ToArray(IEnumerable) method forces immediate query evaluation and returns an array that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.

Well, that certainly looks confusing.

  1. returns an array that contains the query results
  2. obtain a cached copy of the query results

From the first sentence, it is clear that no copies of items in the query are made.

From the second sentence, you get a copy of the query results as a whole, but that is a shallow copy since no copies of items in the query are made.

于 2011-01-21T20:25:40.757 回答
2

What it returns is very dependent on which LINQ method you are referring to. But with the exception of the few methods which explicitly copy the enumeration (ToList and ToArray for example) the general pattern is to not copy the input to a new structure. Instead it prefers lazy evaluation.

于 2011-01-21T17:35:36.760 回答