XDracam / unity-corelibrary

Collection of classes and extension methods that make life with Unity3D more comfortable
MIT License
15 stars 3 forks source link

Enumerable Extension: Try Get Index Of #56

Open Eregerog opened 4 years ago

Eregerog commented 4 years ago

At some point I needed this method, so i implemented it. Might we worth putting into the corelib


     public static bool TryGetIndexOf<T>(this IEnumerable<T> enumerable, T item, out int index)
        {
            index = 0;
            foreach (var i in enumerable)
            {
                if (i.Equals(item))
                    return true;

                ++index;
            }

            index = -1;
            return false;
        }
XDracam commented 4 years ago

This has one issue: not all IEnumerables are ordered, e.g. enumerating a HashSet may yield a random order.

I was originally about to suggest

Why not just .IndexOf and return -1 per convention?

Well, This approach saves a line, which is nice. And the naming fits the standard library, so that is okay.

Anyways, will think about the problem with a lack of order.