Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is List<T>.IndexOf() implemented in C#?

I was thinking about the performance of calling List<T>.Indexof(item). I am not sure if it will be a O(n) performance for a sequential algorithm or O(log(n)) performance for a binary tree??

like image 347
Frank Avatar asked Mar 29 '10 17:03

Frank


People also ask

How to use FindIndex in c#?

FindIndex(Predicate<T>) Method Syntax: public int FindIndex (Predicate<T> match); Parameter: match: It is the Predicate<T> delegate that defines the conditions of the element to search for. Return Value: It returns the index of the first occurrence of an element that matches the conditions defined by match, if found.

Does list have Index 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.

What does IndexOf return if not found 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.


2 Answers

Using Reflector for .NET we can see:

public int IndexOf(T item) {     return Array.IndexOf<T>(this._items, item, 0, this._size); }  public static int IndexOf<T>(T[] array, T value, int startIndex, int count) {     return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count); }  internal virtual int IndexOf(T[] array, T value, int startIndex, int count) {     int num = startIndex + count;     for (int i = startIndex; i < num; i++)     {         if (this.Equals(array[i], value))             return i;     }     return -1; } 
like image 71
abatishchev Avatar answered Sep 22 '22 04:09

abatishchev


It's O(n) according to MSDN.

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

like image 26
IVlad Avatar answered Sep 22 '22 04:09

IVlad