代码之家  ›  专栏  ›  技术社区  ›  mpen

获取IEnumerable的长度?

  •  2
  • mpen  · 技术社区  · 15 年前

    获取.net长度的最快方法是什么 IEnumerable<T> len() 函数似乎不起作用。

    我知道我能做到

    len(list(my_enumerable))
    

    list(my_enumerable).Count
    

    但这可能比必要的要慢。

    1 回复  |  直到 15 年前
        1
  •  7
  •   Luke Woodward    15 年前

    事实上 IEnumerable<T> ? 如果是的话,你可以用 Enumerable.Count(IEnumerable<T> source) (LINQ到对象的一部分)。

    IEnumerable

    public static int Count(IEnumerable source)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
    
        // Optimization for ICollection implementations (e.g. arrays, ArrayList)
        ICollection collection = source as ICollection;
        if (collection != null)
        {
            return collection.Count;
        }
    
        IEnumerator iterator = source.GetEnumerator();
        try
        {
            int count = 0;
            while (iterator.MoveNext())
            {
                count++;
            }
            return count;
        }
        finally
        {
            IDisposable disposable = iterator as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
    }
    

    请注意,在末尾处理迭代器很重要—但是不能使用 using 声明为 IEnumerator 它本身没有实现 IDisposable (不像 IEnumerator<T> ).

    推荐文章