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

17,270

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.

Share:
17,270
Ayo Adesina
Author by

Ayo Adesina

Channel 4 #Hunted Winner 2016

Updated on June 08, 2022

Comments

  • Ayo Adesina
    Ayo Adesina almost 2 years

    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?