IEnumberable到我可以得到一个计数的东西?

Mat*_*wdy 0 c# collections ienumerable

我有这个:

private IEnumerable _myList;
Run Code Online (Sandbox Code Playgroud)

我需要计算一下该物体的数量.我以前在数组中键入_myList并获取长度,但现在我们使用不同类型的对象使用相同的代码.它仍然是一个Collection类型(它是一个强类型的Subsonic Collection对象),一切都很好,除了我们需要获得对象中项目总数的位.

我已经尝试将它输入到CollectionBase和许多其他类型,但没有任何作品可以让我获得.Count或.Length或类似的东西.

谁能指出我正确的方向?

编辑:我没有使用3.5,我正在使用2.所以,任何与Linq有关的事都行不通.很抱歉没有发布此内容.

Jon*_*eet 11

这实际上是IEnumerable代替IEnumerable<T>吗?如果是这样,LINQ将不会直接帮助您.(您可以Cast<T>()按照其他地方的建议使用,但这将相对较慢 - 特别是,它不会针对IList/ IList<T>implementation 进行优化.)

我建议你写一下:

public static int Count(this IEnumerable sequence)
{
    if (sequence == null)
    {
        throw new ArgumentNullException("sequence");
    }

    // Optimisation: won't optimise for collections which
    // implement ICollection<T> but not ICollection, admittedly.
    ICollection collection = sequence as ICollection;
    if (collection != null)
    {
        return collection.Count;
    }

    IEnumerator iterator = sequence.GetEnumerator();
    try
    {
        int count = 0;
        while (iterator.MoveNext())
        {
            // Don't bother accessing Current - that might box
            // a value, and we don't need it anyway
            count++;
        }
        return count;
    }
    finally
    {
        IDisposable disposable = iterator as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 因为并非所有IEnumerator都是IDisposables,所以我打赌. (4认同)

Ken*_* K. 10

System.Linq.Enumerable.Count扩展方法做这行的类型化IEnumerable<T>.对于无类型IEnumerable尝试制作您自己的扩展程序:

    public static int Count(this IEnumerable source)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }

        ICollection collectionSource = source as ICollection;
        if (collectionSource != null)
        {
            return collectionSource.Count;
        }

        int num = 0;
        IEnumerator enumerator = source.GetEnumerator();
        //try-finally block to ensure Enumerator gets disposed if disposable
        try
        {
            while (enumerator.MoveNext())
            {
                num++;
            }
        }
        finally
        {
            // check for disposal
            IDisposable disposableEnumerator = enumerator as IDisposable;
            if(disposableEnumerator != null)
            {
                disposableEnumerator.Dispose();
            }
        }
        return num;
    }
Run Code Online (Sandbox Code Playgroud)