如何根据派生类字段筛选基类集合

本文关键字:筛选 基类 集合 字段 何根 派生 | 更新日期: 2023-09-27 18:14:58

假设我有一个名为MyThings的集合,它包含类Thing的对象,我有一个名为ShinyThing的类,它派生自Thing,所以我做:

MyThings boxWithMyThings = new MyThings();
ShinyThing Diamond = new ShinyThing(){ facets =  10; weight = 500 };
boxWithMyThings.Add(Diamond);

我如何使用派生类的属性过滤集合boxWithMyThings ?

如何根据派生类字段筛选基类集合

想必你只想要ShinyThings?如果是,使用OfType:

// I'm assuming MyThings implements IEnumerable<MyThing>
var heavyShinyThings = boxWithMyThings.OfType<ShinyThing>()
                                      .Where(x => x.weight > 100);

您可以尝试使用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;
     });