在IList.IndexOf()之类的东西,但在IEnumerable ?
在IEnumerable上是否有任何方法/扩展方法允许我在其中找到对象实例的索引? 像IList中的IndexOf()?
indexPosition = myEnumerable.IndexOf() ?
谢谢
IEnumerable
不是有序集。
尽管大多数IEnumerables都是有序的,但有些(例如Dictionary
或HashSet
)却没有。
因此,LINQ没有IndexOf
方法。
但是,你可以自己写一个:
///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)); }
可枚举的扩展方法第二部分 – 索引注入和索引提取 http://chaowchaow.blogspot.com/2008/05/extension-methods-for-enumerable-part.html
请注意,可能没有任何实例方法,因为IEnumerable
是协变的。
任何类型的IEnumerable
都必须实现IndexOf(string x)
,并且由于协方差,可以将其转换为IEnumerable
。
所以它现在公开为IndexOf(object x)
什么是真正的IndexOf(string x)
,并且由于并非所有objects
都是strings
,因此无法对所有对象起作用。
IList
可以这样做,因为它是不变的,即你不能将IList
IList
转换为IList
。