Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of an element in an IEnumerable?

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?

like image 833
Jader Dias Avatar asked Aug 17 '09 21:08

Jader Dias


People also ask

How do I access items in IEnumerable?

var item = eLevelData. ElementAt(index); If your collection is typed as IEnumerable instead of IEnumerable<T> you'll need to use the Cast extension method before you can call ElementAt e.g.

How do I use ElementAt?

The ElementAt() method returns an element from the specified index from a given collection. If the specified index is out of the range of a collection then it will throw an Index out of range exception. Please note that index is a zero based index.

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.


2 Answers

I'd question the wisdom, but perhaps:

source.TakeWhile(x => x != value).Count(); 

(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 way

public static int IndexOf<T>(this IEnumerable<T> source, T value) {     int index = 0;     var comparer = EqualityComparer<T>.Default; // or pass in as a parameter     foreach (T item in source)     {         if (comparer.Equals(item, value)) return index;         index++;     }     return -1; } 
like image 77
Marc Gravell Avatar answered Sep 23 '22 09:09

Marc Gravell


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.

like image 42
Scott Dorman Avatar answered Sep 23 '22 09:09

Scott Dorman