Исключить типы из IEnumerable с помощью linq

Как мне отфильтровать объекты на основе их производного типа с помощью 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));
8
задан Aphelion 6 February 2012 в 15:52
поделиться