显示列表中的对象计数

问题描述 投票:0回答:1

我有一个列表

List<IVehicle> vehicles = new List<IVehicle>();
,在该列表中我想存储对象(汽车、船、Mc)。如何打印列表中有多少个前车对象?

我尝试使用 LINQ

int count = vehicles.Count(x => x == car);
,但现在计数正确。

c# list
1个回答
0
投票

在这一行中:

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

不清楚

car
是什么。

但是无论如何,如果您想计算您需要的

Car
的实例:

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

注意使用 is 运算符来检查实例是否属于特定类型。

© www.soinside.com 2019 - 2024. All rights reserved.