Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of an object in a Generic list

Tags:

c#

list

generics

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);
like image 269
user437631 Avatar asked Mar 24 '11 12:03

user437631


People also ask

Do lists have indexes C#?

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.

How does IndexOf work in C#?

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.

How do I get the length of a list in C#?

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.

Do C# lists start at 0?

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.


4 Answers

The method you want is FindIndex(Predicate)

int index = list.FindIndex(MiniMapRecord p => p.IDa == IDa.SystemID & p.IDb == pInputRecordMap.IDb);
like image 185
MattDavey Avatar answered Oct 17 '22 19:10

MattDavey


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

like image 22
Josh G Avatar answered Oct 17 '22 19:10

Josh G


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.

like image 6
dandan78 Avatar answered Oct 17 '22 19:10

dandan78


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

like image 4
jonsca Avatar answered Oct 17 '22 17:10

jonsca