将 EntityObject 项的列表枚举为特定 EF 对象的列表
在我的 DAL 中,我有一个数据访问对象,用于将数据库记录检索到 EntityObject 列表:
private List<EntityObject> entities;
var pList = context.Products.Where(...);
entities = new List<EntityObject>(pList);
要在我的 BI 层中使用此列表,我需要通过此 List
枚举为 列表>产品
对象。我可以像这样轻松地转换回来:
var pList = Data.Entities.Select(p => p as Product);
但这是否会创建 List
的副本,使该集合的内存占用量加倍,这对于大型集合来说是一个问题?
如果是这样,有没有办法通过此 List
作为 List
进行枚举,而不是转换回 Product
并枚举通过那个副本?
In my DAL I have a data access object that retrievs database records to an EntityObject List:
private List<EntityObject> entities;
var pList = context.Products.Where(...);
entities = new List<EntityObject>(pList);
To work with this List in my BI layer I need to enumarate through this List<EntityObject>
as a list of Product
objects. I can easily convert back like this:
var pList = Data.Entities.Select(p => p as Product);
but doesn't this create a copy of the List<EntityObject>
doubling my memory footprint for this collection which would be a concern with large collections?
If so, is there a way to enumarete through this List<EntityObject>
as List<Product>
instead of converting back to Product
and than enumerating through that copy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这只会复制实体的引用,因此不必担心。
另外一种更安全的方法是:
或者您可以直接枚举产品:
No, this would just make a copy of the references to the entities, so that should be of no concern.
Also a safer way to do your cast would be:
Or you can just directly enumerate through the products:
不,仅调用
Select()
(后面不使用ToList()
或new List()
)不会创建另一个List
,所以你不必担心内存占用。它的作用是使用您提供的 lambda 计算Products
序列。如果 lambda 包含一些复杂的计算,并且您多次迭代结果,则可能会导致性能问题,但这里的情况并非如此。您可以使用两种替代方法来表达相同的转换,但它们有一些差异,当列表包含不是
Product
的对象时,会发生什么情况:Select(p => p作为产品)
:您现在正在使用的产品。如果序列包含不是Product
的对象,它们将变成null
。OfType()
:非Products
将被过滤掉。Cast()
:如果序列包含非Product
,则会抛出异常。这可能是您想要的版本。No, calling just
Select()
(without following it withToList()
ornew List()
) does not create anotherList
, so you don't have to worry about memory footprint. What it does is that it computes the sequence ofProducts
using the lambda you provided. If the lambda contained some complicated computation and you iterated over the result several times, this could cause performance problems, but that's not the case here.There are two alternative ways that you could use to express the same cast, but they have some differences what happens when the list contains objects that are not
Product
s:Select(p => p as Product)
: the one you're using right now. If the sequence contains objects that are notProduct
s, they will turn intonull
s.OfType<Product>()
: non-Products
will be filtered out.Cast<Product>()
: if the sequence contains non-Product
s, it throws an exception. This is probably the version you want.