user437631
user437631

Reputation: 1112

Get index of an object in a Generic list

I have a list of custom objects with two properties as identifiers (IDa and IDb).

Every time I remove an object I need to know its index. How do I get an index of an object without looping all the list?

List<CustomObject> list = new List<CustomObject>();
list.RemoveAll((MiniMapRecord p) => p.IDa == IDa.SystemID & p.IDb == pInputRecordMap.IDb);

Upvotes: 14

Views: 37617

Answers (4)

jonsca
jonsca

Reputation: 10381

Use the .IndexOf() method of the list to find the index, and then use .RemoveAt() to remove it.

Upvotes: 4

Josh G
Josh G

Reputation: 14266

As others have stated, there's no way to avoid looping through the items to find one unless you either:

Remember the indexes. When you create the list, save the relevant indexes to a member variable. This may not be appropriate for your problem.

Or:

Keep the list sorted and do a binary search for the item. This also may not work because you have two identifiers.

IndexOf() is a simple solution, but it will cost O(N) (linear).

Upvotes: 8

MattDavey
MattDavey

Reputation: 9027

The method you want is FindIndex(Predicate)

int index = list.FindIndex(MiniMapRecord p => p.IDa == IDa.SystemID & p.IDb == pInputRecordMap.IDb);

Upvotes: 21

dandan78
dandan78

Reputation: 13925

You can use the IndexOf() method to get the index of a given element of your List<>.

However, note that since a linked list implies no random access, there really isn't any other way to find a specific element (and consequently its index) other than starting from the beginning and checking one element at a time.

Upvotes: 6

Related Questions