Search code examples
c#listinheritancecasting

How to filter items from collection based on type stored in variable


I have the following hierarchy:

class Animal

class Dog : Animal

class Cat : Animal

I have a List<Animal> collection and want to make a method that will return all cats or all dogs. However I can't figure out how to filter the list elements based on a type variable. So like this:

int AnimalsOfType(Type animalType)
{
    // Gives error "animalType is a variable but is used like a type".
    return animals.OfType<animalType>().Count;
}

Solution

  • using System.Linq;
    
    int AnimalsOfType(Type animalType)
    {
        return animals.Count(a => a.GetType() == animalType);
    }