I wrote this:
public static class EnumerableExtensions
{
public static int IndexOf<T>(this IEnumerable<T> obj, T value)
{
return obj
.Select((a, i) => (a.Equals(value)) ? i : -1)
.Max();
}
public static int IndexOf<T>(this IEnumerable<T> obj, T value
, IEqualityComparer<T> comparer)
{
return obj
.Select((a, i) => (comparer.Equals(a, value)) ? i : -1)
.Max();
}
}
But I don't know if it already exists, does it?
A few years later, but this uses Linq, returns -1 if not found, doesn't create extra objects, and should short-circuit when found [as opposed to iterating over the entire IEnumerable]:
Where 'FirstOr' is:
Using @Marc Gravell 's answer, I found a way to use the following method:
in order to get -1 when the item cannot be found:
I guess this way could be both the fastest and the simpler. However, I've not tested performances yet.
A bit late in the game, i know... but this is what i recently did. It is slightly different than yours, but allows the programmer to dictate what the equality operation needs to be (predicate). Which i find very useful when dealing with different types, since i then have a generic way of doing it regardless of object type and
<T>
built in equality operator.It also has a very very small memory footprint, and is very, very fast/efficient... if you care about that.
At worse, you'll just add this to your list of extensions.
Anyway... here it is.
Hopefully this helps someone.
The best way to catch the position is by
FindIndex
This function is available only forList<>
Example
If you have enumerator or array use this way
or
Stumbled across this today in a search for answers and I thought I'd add my version to the list (No pun intended). It utlises the null conditional operator of c#6.0
I've done some 'racing of the old horses' (testing) and for large collections (~100,000), worst case scenario that item you want is at the end, this is 2x faster than doing
ToList().FindIndex()
. If the Item you want is in the middle its ~4x faster.For smaller collections (~10,000) it seems to be only marginally faster
Heres how I tested it https://gist.github.com/insulind/16310945247fcf13ba186a45734f254e
This can get really cool with an extension (functioning as a proxy), for example:
Which will automagically assign indexes to the collection accessible via this
Index
property.Interface:
Custom extension (probably most useful for working with EF and DbContext):