如何获取 ICollection<T> 中项目的索引

How to get Index of an Item in ICollection<T>

我有这份汽车清单

ICollection<Cars> Cars

而且我还有一个汽车对象,我知道它在 ICollection 中如何获得列表中汽车的 index/position?我需要将它添加到字符串列表

这是我目前拥有的:

var index = cars.Where(b=> b.Id == car.id).Single().iWantTheIndex
stringList.Add(index)

有什么想法吗?

如果您想使用索引集合,那么您应该使用 IList<T>,而不是 ICollection<T>ICollection<T> 是您可以枚举、添加和删除项目以及获取计数的东西,仅此而已。 IList<T> 是一个集合,其中的项目按指定的顺序排列,可以根据它们在列表中的位置进行访问。

因为 ICollection<T> 不一定代表有序集合,所以您无法获得有意义的 "index" 项目。项目不一定 位置。

这将为您提供 当前 迭代的索引:

var index = cars.Select((c, i) => new{ Index = i, Car = c })
                .Where(item => item.Car.Id == car.id)
                .Single()
                .Index;

stringList.Add(index);

请注意 next 迭代可能有不同的顺序(取决于您的 ICollection<> 的实际实现)并且可能导致完全不同的索引,所以小心你使用这个索引的目的。