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 is
is best. You can shorten the code to just .Where(animal => !(animal is Duck));
Otherwise, sll's recommendation of GetType is best
Except()
is quite heavy.Keep in mind that solution is
- would return true even some SomeDuck
class inherited from Duck
class SomeDuck : Duck
...
// duck is Duck == true
var duck = new SomeDuck();
An other solution could be:
animals.Where(animal => animal.GetType() != typeof(Duck))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With