Does LINQ update memory when creating returns

Does LINQ do a deep copy of the results in another list / array / etc or just give me a list / array / etc. consisting of links to the original?

+6
linq deep-copy shallow-copy
source share
3 answers

It depends on whether you use (and how) to select the results.

If you do not create new objects in the projection, the result will refer to 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 

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 noting 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 links in the collection will be different.

Basically - nothing in .Net except serializers (as mentioned elsewhere here) will be a β€œdeep” copy if you do not 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 taking place here. Of course, the Clone implementation will be in the class and can be anything, including deep copying, but this is not indicated.

+10
source share

Does LINQ do a deep copy of the results in another list / array / etc or just give me a list / array / etc. consisting of links to the original?

From Enumerated .ToArray . (Character text found in Enumerable.ToList )

The ToArray (IEnumerable) method calls an immediate query evaluation and returns an array containing the query results. You can add this method to your query to get a cached copy of the query results.

Well, it definitely looks confusing.

  • returns an array containing the query results
  • get a cached copy of query results

From the first sentence, it is clear that no copies of the elements in the request were made.

From the second sentence, you get a copy of the results of the query as a whole, but this is a shallow copy, since copies of the elements in the query are not made.

+3
source share

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

+2
source share

All Articles