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 LightEntity
s and PlayerEntity
s.
I wish to get all the LightEntity
s 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
.
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
just cast the ent to (LightEntity) so
Lights.Add((LightEntity)ent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With