Search code examples
c#listlinq

Counting objects of specific type in List<T>


I have a list List<IVehicle> vehicles = new List<IVehicle>(); and in that list I want to store objects (Car, Boat, Mc) that implement IVehicle.

How can I print out how many objects of ex Car I have in the list?

I tried using LINQ:

int count = vehicles.Count(x => x == car);

but it does now count correct.


Solution

  • Assuming all your Car,Boat,Mc objects implement IVehicle:

    You can achieve this by using OfType<T> method which is LINQ extension method.

    int count = vehicles.OfType<Car>().Count();
    

    OfType<T> method as stated by Microsoft document:

    Filters the elements of an IEnumerable based on a specified type.