Showing objects count in list

112 Views Asked by At

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.

2

There are 2 best solutions below

0
Hr.Panahi On BEST ANSWER

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.

2
wohlstad On

In this line:

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

It is not clear what car is. If is it a specific object of type Car you will get the number of elements that are equal to that object.

But anyway if you want to count all elements which are instances of type Cars you need:

//------------------------------vvvvvvvv--
int count = vehicles.Count(x => x is Car);

Note the usage of the is operator to check if an object is of a specific type.