c# - 使用 linq 从 IEnumerable 中排除类型

标签 c# linq linq-to-objects

如何使用 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/

相关文章:

c# - 根据是否重复返回true或false

c# - Linq to objects 列表中的列表

c# - 对数据表的 LINQ 查询返回不正确的结果

c# - 为什么要升级到 c# 4.0?

c# - 由外键 ef 4.3 组成的代码优先组合键

c# - 'IdLogement' Azure 移动服务查询不支持成员 'Where'

linq - 这个 RavenDB linq 查询是如何工作的

c# - Linq 查询 - 在另一个列表中列出

c# - 返回两个值,这些值紧邻IEnumerable <float>中的测试值

c# - 登录后如何在下一个表单的标签中显示欢迎用户名?