使用 linq 从 IEnumerable 中排除类型
如何使用 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));
How can I filter out objects based on their derived type with linq-to-objects?
I am looking for the solution with the best performance.
The classes used:
abstract class Animal { }
class Dog : Animal { }
class Cat : Animal { }
class Duck : Animal { }
class MadDuck : Duck { }
I know of three methods: Use the is
keyword, use the Except
method, and to use the OfType
method.
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));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您还想排除 Duck 的子类,那么
is
是最好的。您可以将代码缩短为.Where(animal => !(animal is Duck));
否则,sll 推荐的 GetType 是最好的
If you want to also exclude subclasses of Duck, then the
is
is best. You can shorten the code to just.Where(animal => !(animal is Duck));
Otherwise, sll's recommendation of GetType is best
Except()
的解决方案相当繁重。请记住,解决方案
是
- 即使某些从Duck
继承的SomeDuck
类也会返回true其他解决方案可以是:
Except()
is quite heavy.Keep in mind that solution
is
- would return true even someSomeDuck
class inherited fromDuck
An other solution could be:
根据 OfType<>() 和检查类型之间的差异Where() 扩展 OfType 调用等效于您的选项 (a),尽管 is Duck==true,因此基于此我会说坚持选项 (a)。
According to Difference between OfType<>() and checking type in Where() extension the OfType call is equivalent to your option (a), albeit with is Duck==true, so based on that I would say stick to option (a).
如果您不希望返回
Duck
或Duck
的任何子类,则需要使用IsAssignableFrom
方法:If you don't want
Duck
nor any subclass ofDuck
to be returned, you need to use theIsAssignableFrom
method: