2

假设我有一个名为的集合MyThings,其中包含该类的对象,Thing并且我有一个名为的类ShinyThing,它是从 派生的Thing,所以我这样做:

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

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

4

2 回答 2

4

大概你只想要ShinyThings?如果是这样,请使用OfType

// I'm assuming MyThings implements IEnumerable<MyThing>
var heavyShinyThings = boxWithMyThings.OfType<ShinyThing>()
                                      .Where(x => x.weight > 100);
于 2013-05-22T20:33:28.573 回答
2

您可以尝试使用该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;
     });
于 2013-05-22T20:34:11.610 回答