Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 844
Ayo Adesina Avatar asked Nov 15 '17 15:11

Ayo Adesina


2 Answers

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.

like image 101
Servy Avatar answered Sep 18 '22 12:09

Servy


This will give you the index of the current iteration:

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

stringList.Add(index);

Please note that the next iteration may have a different order (depending on the actual implementation of your ICollection<>) and may result in a completely different index, so be careful what you use this index for.

like image 43
nvoigt Avatar answered Sep 19 '22 12:09

nvoigt