How to get the index of an item in a list in a single step?

Daniel Robinson picture Daniel Robinson · Aug 1, 2013 · Viewed 436.2k times · Source

How can I find the index of an item in a list without looping through it?

Currently this doesn't look very nice - searching through the list for the same item twice, just to get the index:

var oProp = something;

int theThingIActuallyAmInterestedIn = myList.IndexOf(myList.Single(i => i.Prop == oProp));

Answer

Alex Filipovici picture Alex Filipovici · Aug 1, 2013

How about the List.FindIndex Method:

int index = myList.FindIndex(a => a.Prop == oProp);

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

If the item is not found, it will return -1