开发者

Get index of an object in a Generic list

开发者 https://www.devze.com 2023-02-19 05:43 出处:网络
I have a li开发者_JAVA技巧st of custom objects with two properties as identifiers (IDa and IDb).

I have a li开发者_JAVA技巧st 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);


The method you want is FindIndex(Predicate)

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


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).


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消