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));
If you want to also exclude subclasses of Duck, then the
isis best. You can shorten the code to just.Where(animal => !(animal is Duck));Otherwise, sll’s recommendation of GetType is best