如何获得的元素的在一个IEnumerable索引? [英] How to get the index of an element in an IEnumerable?

查看:1265
本文介绍了如何获得的元素的在一个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屋!

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