如何使用 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 的子类,那么 is
是最好的。您可以将代码缩短为 .Where(animal => !(animal is Duck));
否则sll推荐的GetType最好
关于c# - 使用 linq 从 IEnumerable 中排除类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9097798/