UCC
UCC

Reputation: 13

Can I retrieve the index position of an element in a list?

I have the following list:

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?

Upvotes: 1

Views: 157

Answers (6)

ecMode
ecMode

Reputation: 540

_cars.indexof(T) Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.

Upvotes: 1

BonyT
BonyT

Reputation: 10940

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

Upvotes: 4

Jamie Curtis
Jamie Curtis

Reputation: 916

Car car = new Car(...);
_cars.IndexOf(car);

Upvotes: 1

Jonathan
Jonathan

Reputation: 12015

Check IndexOf Method : MSDN

Upvotes: 2

rid
rid

Reputation: 63542

You can use List.IndexOf(). Check out the List Class reference for more about what you can do with a list.

Upvotes: 1

Bala R
Bala R

Reputation: 108977

List<T>.IndexOf(T)

MSDN has a good example.

Upvotes: 1

Related Questions