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

Ayo Adesina picture Ayo Adesina · Nov 15, 2017 · Viewed 13k times · Source

I have this list of cars

ICollection<Cars> Cars

and I also have a single car object, which I know is in the ICollection how do I get the index/position of the car in the list? I need to add it to a list of strings

This is what I have so far:

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

Any ideas?

Answer

Servy picture Servy · Nov 15, 2017

If you want to use an indexed collection then you should use IList<T>, not ICollection<T>. An ICollection<T> is something that you can enumerate, add and remove items for, and get the count of, that's all. An IList<T> is a collection in which the items are in a specified order, and can be accessed based on their position in the list.

Because an ICollection<T> doesn't necessarily represent an ordered collection, you cannot get a meaningful "index" of an item. Items don't necessarily have a position.