Propose: new method Enumerable.IndexOf


#1

Hi, I would like to propose a new member for Enumerable class:

int IndexOf<T>(IEnumerable<T> source, T item, IEqualityComperer<T> comparer)

It’s useful to find the index of an item inside the source. Only IList has a similar method but it force me to completely materialize all the source. The implementation can enumerate list or, if the original source type is IList, call the IList.IndexOf method. If the source type is an Array we can call Array.IndexOf.

What do you think?


#2

I believe the right place for such proposals is the CoreFx repo.


#3

Strictly speaking, there’s no guarantee that an IEnumerable will be the same every time you enumerate it … so getting back an index, and then subsequently trying to fetch it at that index might prove to be unfortunate. If you need to index into a sequence, just call .ToList or .ToArray. Having a method like this available would set the wrong expectations of the API (IMO :stuck_out_tongue: ).

That being said, it’s really easy to add these to a utility file in your own project … such as: https://gist.github.com/JohanOtto/7dc784b4f41a553c7d21


.NET Foundation Website | Blog | Projects | Code of Conduct