LINQ创建返回时是否新建内存
LINQ 实际上是否将结果深层复制到不同的列表/数组/等,或者它只是给我一个列表/数组/等。由对原文的引用组成?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将取决于您是否(以及如何)使用“选择”来预测结果。
如果您不在投影中创建新对象,则结果将引用与原始集合相同的对象。
但是,如果您在项目中创建新对象,那么显然它们将不一样。
此处返回的集合将包含对
_myCollection
中相同对象的引用:在这些情况下返回的集合不会:
在这种情况下,值得指出的是新匿名对象的 Prop1 和 Prop2 - 如果它们是引用类型 - 将包含对与原始对象相同的对象的引用。只有集合中的顶级引用会有所不同。
基本上 - 除了序列化器(如这里其他地方提到的)之外,.Net 中没有任何东西会“深度”复制,除非你实现它。
或者
再次强调,假设此处发生任何“深度”复制是错误的。当然,
Clone
的实现将在类中,并且可以是任何内容,包括深度复制,但没有给出。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
:The collections returned in these cases will not:
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
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.来自Enumerable.ToArray。 (在 Enumerable.ToList 中找到类似的文本)
嗯,这看起来确实令人困惑。
从第一句中可以清楚地看出,没有创建查询中的项目副本。
从第二句话中,您将获得整个查询结果的副本,但这是一个浅副本,因为没有创建查询中的项目副本。
From Enumerable.ToArray. (Similiar text found at Enumerable.ToList)
Well, that certainly looks confusing.
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.
它返回的内容很大程度上取决于您所引用的 LINQ 方法。但除了少数显式复制枚举的方法(例如
ToList
和ToArray
)之外,一般模式是不将输入复制到新结构。相反,它更喜欢惰性评估。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
andToArray
for example) the general pattern is to not copy the input to a new structure. Instead it prefers lazy evaluation.