Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a List of objects with the same base class and extracting a certain class?

For example, I have a base class Entity, then two sub classes that derive from this, LightEntity and PlayerEntity.

I then have a List<Entity> Entities that holds LightEntitys and PlayerEntitys.

I wish to get all the LightEntitys from Entities.

I tried:

List<LightEntity> lights = new List<LightEntity>();
foreach (Entity ent in Entities)
{
    if(ent is LightEntity)
    {
        lights.Add(ent);
    }
}

But it doesn't like this as the compiler still seems to think that it might try to add just an Entity to a list of LightEntity.

I tried to cast ent to LightEntity but the compiler says it has no methods of converting an Entity to a LightEntity.

like image 918
MatthewMcGovern Avatar asked May 09 '13 21:05

MatthewMcGovern


2 Answers

You could use OfType to filter the entities by type:

List<LightEntity> lights = new List<LightEntity>();
lights.AddRange(entities.OfType<LightEntity>());

Or even easier:

List<LightEntity> lights = entities.OfType<LightEntity>().ToList();

Further Reading

  • Getting Started with LINQ in C#
like image 128
p.s.w.g Avatar answered Oct 17 '22 01:10

p.s.w.g


just cast the ent to (LightEntity) so

Lights.Add((LightEntity)ent);
like image 26
Kyle C Avatar answered Oct 17 '22 01:10

Kyle C