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

前端 未结 3 1609
旧巷少年郎
旧巷少年郎 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条回答
  •  -上瘾入骨i
    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:

    ///Finds the index of the first item matching an expression in an enumerable.
    ///The enumerable to search.
    ///The expression to test the items against.
    ///The index of the first matching item, or -1 if no items match.
    public static int FindIndex(this IEnumerable items, Func 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;
    }
    ///Finds the index of the first occurence of an item in an enumerable.
    ///The enumerable to search.
    ///The item to find.
    ///The index of the first matching item, or -1 if the item was not found.
    public static int IndexOf(this IEnumerable items, T item) { return items.FindIndex(i => EqualityComparer.Default.Equals(item, i)); }
    

提交回复
热议问题