栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用LINQ获取索引?[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用LINQ获取索引?[重复]

An

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 occurrence 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)); }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416907.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号