Can I retrieve the index position of an element in a list?
I have the following list:
开发者_JS百科private List<Car> _cars = new List<Car>();
I know I can check the size of the list with _cars.Count() but is it also possible for me to find out the sequence number of a Car item in the list?
The "Sequence Number" you are after is referred to as Index:
If you define a Car:
Car myCar = new Car(){Make = "Ford", Model="Escort"};
_cars.Add(myCar);
Then you obtain the Index as follows:
int index = _cars.IndexOf(myCar);
If this is the only item in the list then index will be 0
Check IndexOf Method : MSDN
List<T>.IndexOf(T)
MSDN has a good example.
You can use List.IndexOf()
. Check out the List Class reference for more about what you can do with a list.
Car car = new Car(...);
_cars.IndexOf(car);
_cars.indexof(T) Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.
精彩评论