如何使用LINQ-to-Objects根据派生类型筛选对象?
我正在寻找最佳性能的解决方案。
所用的类:
abstract class Animal { }
class Dog : Animal { }
class Cat : Animal { }
class Duck : Animal { }
class MadDuck : Duck { }
我知道三种方法:使用关键字
is
,使用Except
方法,以及使用OfType
方法。List<Animal> animals = new List<Animal>
{
new Cat(),
new Dog(),
new Duck(),
new MadDuck(),
};
// Get all animals except ducks (and or their derived types)
var a = animals.Where(animal => (animal is Duck == false));
var b = animals.Except((IEnumerable<Animal>)animals.OfType<Duck>());
// Other suggestions
var c = animals.Where(animal => animal.GetType() != typeof(Duck))
// Accepted solution
var d = animals.Where(animal => !(animal is Duck));
Duck
的MadDuck
,那么它应该被返回还是不应该?另外,你想要实现什么目标?使用is
和运行时类型检查可能会暴露设计问题。 - vgrub
无效,因为它们比较类型而不是继承关系。 - Myrtle