ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IndexOf

Gets the index of the give value in a collection. Is overloaded to take a start parameter as well.

Source

public static int IndexOf<T>(this IEnumerable<T> obj, T value)
{
    return obj.IndexOf(value, 0);
}

public static int IndexOf<T>(this IEnumerable<T> obj, T value, int start)
{
    if (start >= obj.Count()) return -1;
    if (start < 0) throw new IndexOutOfRangeException("start must be a non-negative integer");
    for (int i = start; i < obj.Count(); ++i)
    {
        if (value.Equals(obj.ElementAt(i))) return i;
    }
    return -1;
}

Example

var i = new Collection<int>{0,1,2,3,4,5,6,7};

int first = i.IndexOf(0);
int second = i.IndexOf(0,1);

Author: Daniel Gidman

Submitted on: 3 dec. 2010

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 5686