东西的IList.IndexOf(),但是,IEnumerable的&LT喜欢; T>? [英] Something in the likes of IList.IndexOf() but on IEnumerable<T>?

查看:123
本文介绍了东西的IList.IndexOf(),但是,IEnumerable的&LT喜欢; T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有IEnumerable的任何方法/扩展方法,可以让我找到一个对象实例的指数?像的IndexOf()的IList的?

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 = myEnumerable.IndexOf() ?

感谢

推荐答案

这是的IEnumerable 不是一个有序集合。
虽然大多数IEnumerables是有序的,有的(如词典的HashSet )都没有。

An IEnumerable is not an ordered set.
Although most IEnumerables are ordered, some (such as Dictionary or HashSet) are not.

因此​​,LINQ不具有的IndexOf 方法。

Therefore, LINQ does not have an IndexOf method.

不过,你可以写一个自己:

However, you can write one yourself:

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

这篇关于东西的IList.IndexOf(),但是,IEnumerable的&LT喜欢; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆