创建返回时LINQ是否会增加内存 [英] Does LINQ new up memory when creating returns

查看:84
本文介绍了创建返回时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?

推荐答案

这将取决于您是否(以及如何)使用Select来投影结果.

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.

此处返回的集合将包含对_myCollection中相同对象的引用:

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 }

在这种情况下,值得指出的是,新匿名对象的Prop1和Prop2(如果它们是引用类型)将包含对 same 对象的引用作为原始对象.只有集合中的顶级引用会有所不同.

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.

基本上-.Net中除序列化程序(如此处其他地方所述)外的任何内容都不会深化"副本,除非您实施它.

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

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

同样,假设这里正在进行任何深度"复制将是一个错误.当然,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.

这篇关于创建返回时LINQ是否会增加内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆