您可以尝试使用该OfType
方法,只要boxWithMyThings
实现IEnumerable<Thing>
:
var filtered = boxWithMyThings.OfType<ShingThing>().Where(st => st.facets == 10);
如果要过滤多种类型(不仅ShinyThings
可以Concat
与许多类似的调用一起使用:
IEnumerable<Thing> shinyEnough = boxWithMyThings.OfType<ShingThing>().Where(st => st.shininess >= 10);
IEnumerable<Thing> dirtyEnough = boxWithMyThings.OfType<DirtyThing>().Where(dt => dt.dirtiness >= 10);
var veryDirtyAndVeryCleanObjects = shinyEnough.Concat(dirtyEnough);
当然,您可以通过检查类型和强制转换,将Where
这里的所有谓词放入一个大Where
子句中,这样可读性可能会降低,但效率会更高:
boxWithMyThings.Where(t =>
{
if (t is ShinyThing)
return (t as ShinyThing).shininess >= 10;
else if (t is DirtyThing)
return (t as DirtyThing).dirtiness >= 10;
else return false;
});