Something in the likes of IList.IndexOf() but on IEnumerable?

前端 未结 3 1630
旧巷少年郎
旧巷少年郎 2021-02-20 12:17

Is there any method / extension method on IEnumerable that allows me to find the index of of an object instance in it? Like IndexOf() in IList?

indexPosition = m         


        
相关标签:
3条回答
  • 2021-02-20 12:37

    Note that there couldn't be any instance method because IEnumerable is covariant.

    Anything of type IEnumerable<string> has to implement IndexOf(string x), and, due to covariance, can be casted to IEnumerable<object>.

    So it now exposes as IndexOf(object x) what is really IndexOf(string x), and since not all objects are strings, couldn't work for all objects.

    IList can do it because it's invariant, i.e. you can't cast an IList<string> to an IList<object>.

    0 讨论(0)
  • 2021-02-20 12:39

    An IEnumerable is not an ordered set.
    Although most IEnumerables are ordered, some (such as Dictionary or HashSet) are not.

    Therefore, LINQ does not have an IndexOf method.

    However, you can write one yourself:

    ///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
    ///<param name="items">The enumerable to search.</param>
    ///<param name="predicate">The expression to test the items against.</param>
    ///<returns>The index of the first matching item, or -1 if no items match.</returns>
    public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
        if (items == null) throw new ArgumentNullException("items");
        if (predicate == null) throw new ArgumentNullException("predicate");
    
        int retVal = 0;
        foreach (var item in items) {
            if (predicate(item)) return retVal;
            retVal++;
        }
        return -1;
    }
    ///<summary>Finds the index of the first occurence of an item in an enumerable.</summary>
    ///<param name="items">The enumerable to search.</param>
    ///<param name="item">The item to find.</param>
    ///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
    public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }
    
    0 讨论(0)
  • 2021-02-20 12:54

    Extension Methods for Enumerable Part II - Index injection and index extraction http://chaowchaow.blogspot.com/2008/05/extension-methods-for-enumerable-part.html

    0 讨论(0)
提交回复
热议问题