Compare/Extract by EntityType

Posts   
 
    
jovball
User
Posts: 443
Joined: 23-Jan-2005
# Posted on: 05-Apr-2012 05:35:08   

Given the following:


List<IEntity2> entityList = new List<IEntity2>();
entityList.Add(new CustomerEntity());
entityList.Add(new EmployeeEntity());
entityList.Add(new OrderEntity());
entityList.Add(new CustomerEntity());
entityList.Add(new ProductEntity());

I have two questions. First, what is the best way for me to get a List<CustomerEntity> from the entityList above?

Second, what is the best way for me to do a foreach loop and find the CustomerEntity objects in entityList?

            
foreach (IEntity2 entity in entityList)
{
Assert.AreEqual(entity.LLBLGenProEntityName, EntityType.CustomerEntity.ToString());
}

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 05-Apr-2012 09:22:02   

Check on the type.

1-

var customers = (from c in entityList
        where c is CustomerEntity
        select c).ToList();

2-

foreach (IEntity2 entity in entityList)
{
    if (entity is CustomerEntity)
    { 
        // do something...
    }
}
jovball
User
Posts: 443
Joined: 23-Jan-2005
# Posted on: 05-Apr-2012 10:46:39   

Yes, to #2. I don't know what I was thinking there.

No, to #1. That gives me a list of the customer entities but the type is still List<IEntity2>. I need to have List<CustomerEntity> as the type.

I might need to use the loop in #2 but was looking for something more like #1.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 05-Apr-2012 11:24:10   

Here you go:

var customers = (from c in entityList
        where c is CustomerEntity
        select c as CustomerEntity).ToList();