c# – 像IList.IndexOf()中的东西,但是在IEnumerable?
发布时间:2020-12-15 06:33:42 所属栏目:百科 来源:网络整理
导读:在IEnumerable中是否有任何方法/扩展方法,允许我找到一个对象实例的索引?像IList中的IndexOf()? indexPosition = myEnumerable.IndexOf() ? 谢谢 解决方法 IEnumerable不是有序集. 虽然大多数IEnumerables都是有序的,但有些(如Dictionary或HashSet)不是.
在IEnumerable中是否有任何方法/扩展方法,允许我找到一个对象实例的索引?像IList中的IndexOf()?
indexPosition = myEnumerable.IndexOf() ? 谢谢 解决方法
IEnumerable不是有序集.
虽然大多数IEnumerables都是有序的,但有些(如Dictionary或HashSet)不是. 因此,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)); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |