如何获取 IEnumerable 中元素的索引? [英] How to get the index of an element in an IEnumerable?
本文介绍了如何获取 IEnumerable 中元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是这样写的:
public static class EnumerableExtensions
{
public static int IndexOf<T>(this IEnumerable<T> obj, T value)
{
return obj
.Select((a, i) => (a.Equals(value)) ? i : -1)
.Max();
}
public static int IndexOf<T>(this IEnumerable<T> obj, T value
, IEqualityComparer<T> comparer)
{
return obj
.Select((a, i) => (comparer.Equals(a, value)) ? i : -1)
.Max();
}
}
但我不知道它是否已经存在,是吗?
But I don't know if it already exists, does it?
推荐答案
将内容作为 IEnumerable 的全部意义在于,您可以懒惰地迭代内容.因此,没有真正索引的概念.对于 IEnumerable,您正在做的事情确实没有多大意义.如果您需要支持按索引访问的内容,请将其放入实际列表或集合中.
The whole point of getting things out as IEnumerable is so you can lazily iterate over the contents. As such, there isn't really a concept of an index. What you are doing really doesn't make a lot of sense for an IEnumerable. If you need something that supports access by index, put it in an actual list or collection.
这篇关于如何获取 IEnumerable 中元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文