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);
The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.
In C#, IndexOf() method is a string method. This method is used to find the zero-based index of the first occurrence of a specified character or string within the current instance of the string. The method returns -1 if the character or string is not found.
Try this: Int32 length = yourList. Count; In C#, arrays have a Length property, anything implementing IList<T> (including List<T> ) will have a Count property.
They are 0 based. Count will start with one however if the list has any items in it. From MSDN if you cared to look it up: Elements in this collection can be accessed using an integer index.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With