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?
An alternative to finding the index after the fact is to wrap the Enumerable, somewhat similar to using the Linq GroupBy() method.
Which gives a use case of:
I would implement it like this:
I think the best option is to implement like this:
It will also not create the anonymous object
The whole point of getting things out as IEnumerable is so you can lazily iterate over the contents. As such, there isn't really a concept of an index. What you are doing really doesn't make a lot of sense for an IEnumerable. If you need something that supports access by index, put it in an actual list or collection.
I'd question the wisdom, but perhaps:
(using
EqualityComparer<T>.Default
to emulate!=
if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long wayThe way I'm currently doing this is a bit shorter than those already suggested and as far as I can tell gives the desired result:
It's a bit clunky, but it does the job and is fairly concise.