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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With