c# - 类似于 IList.IndexOf() 但在 IEnumerable<T> 上的东西?

标签 c# .net ienumerable

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

indexPosition = myEnumerable.IndexOf() ?

谢谢

最佳答案

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

关于c# - 类似于 IList.IndexOf() 但在 IEnumerable<T> 上的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718139/

相关文章:

c# - 用 IEnumerable<> 源填充 Dictionary<>

c# - Mono 无法保存用户设置

c# - C++等效于C#Array.Sort

c# - 如何将异步任务存储在字典中并根据配置值调用它们?

java - Java VM 与 .NET CLR 的性能基准测试

c# - 检查两个列表的修改

performance - 为什么使用 Linq To Objects 时 IQueryable 比 IEnumerable 快两倍

c# - 数据库初始化程序未播种

c# - 如何将对象转换为未知的泛型类型?

c# - 即使在添加所需的命名空间后也会出现“必需”错误