Dean Kuga
Dean Kuga

Reputation: 12119

Enumerating a list of EntityObject items as a list of specific EF objects

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?

Upvotes: 0

Views: 310

Answers (2)

svick
svick

Reputation: 244837

No, calling just Select() (without following it with ToList() or new List()) does not create another List, so you don't have to worry about memory footprint. What it does is that it computes the sequence of Products 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 Products:

  • Select(p => p as Product): the one you're using right now. If the sequence contains objects that are not Products, they will turn into nulls.
  • OfType<Product>(): non-Products will be filtered out.
  • Cast<Product>(): if the sequence contains non-Products, it throws an exception. This is probably the version you want.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160912

but doesn't this create a copy of the List doubling my memory footprint for this collection which would be a concern with large collections?

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:

var pList = Data.Entities.OfType<Product>().ToList();

Or you can just directly enumerate through the products:

foreach(var product in Data.Entities.OfType<Product>())
{
   //..
}

Upvotes: 2

Related Questions