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


for example, have base class entity, 2 sub classes derive this, lightentity , playerentity.

i have list<entity> entities holds lightentitys , playerentitys.

i wish lightentitys entities.

i tried:

list<lightentity> lights = new list<lightentity>(); foreach (entity ent in entities) {     if(ent lightentity)     {         lights.add(ent);     } } 

but doesn't compiler still seems think might try add entity list of lightentity.

i tried cast ent lightentity compiler says has no methods of converting entity lightentity.

you use oftype filter entities type:

list<lightentity> lights = new list<lightentity>(); lights.addrange(entities.oftype<lightentity>()); 

or easier:

list<lightentity> lights = entities.oftype<lightentity>().tolist(); 

further reading


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -