[英]Get index of an object in a Generic list
I have a list of custom objects with two properties as identifiers (IDa, IDb) everytime i remove an object i need to know it's index. 我有一个自定义对象列表,每次删除一个对象我需要知道它的索引时,有两个属性作为标识符(IDa,IDb)。 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);
你想要的方法是FindIndex(谓词)
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). IndexOf()
是一个简单的解决方案,但它将花费O(N)(线性)。
You can use the IndexOf()
method to get the index of a given element of your List<>
. 您可以使用
IndexOf()
方法获取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. 但请注意,由于链接列表不允许随机访问,因此除了从头开始并一次检查一个元素之外,实际上没有任何其他方法可以找到特定元素(以及因此其索引)。
使用列表的.IndexOf()
方法查找索引,然后使用.RemoveAt()
将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.