在IList.IndexOf()之类的东西,但在IEnumerable <T>?

dev*_*ium 10 .net c# ienumerable

在IEnumerable上是否有任何方法/扩展方法允许我在其中找到对象实例的索引?像IList中的IndexOf()一样?

indexPosition = myEnumerable.IndexOf() ?
Run Code Online (Sandbox Code Playgroud)

谢谢

SLa*_*aks 9

An IEnumerable不是有序集.
虽然大多数IEnumerables是有序的,但有些(例如DictionaryHashSet)不是.

因此,LINQ没有IndexOf方法.

但是,你可以自己写一个:

///<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)); }
Run Code Online (Sandbox Code Playgroud)

  • 如果"IEnumerable"并不总是被命令的事实促使缺少`IndexOf`扩展方法,那么为什么我们有`ElementAt`? (8认同)