Difference between IEnumerable Count() and Length

后端 未结 3 1605
感动是毒
感动是毒 2020-11-30 01:21

What are the key differences between IEnumerable Count() and Length?

3条回答
  •  心在旅途
    2020-11-30 02:11

    Little addition to Jon Skeet's comment.

    Here is the source code of the Count() extension method:

    .NET 3:

    public static int Count(this IEnumerable source)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        ICollection is2 = source as ICollection;
        if (is2 != null)
        {
            return is2.Count;
        }
        int num = 0;
        using (IEnumerator enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                num++;
            }
        }
        return num;
    }
    

    .NET 4:

    public static int Count(this IEnumerable source)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        ICollection is2 = source as ICollection;
        if (is2 != null)
        {
            return is2.Count;
        }
        ICollection is3 = source as ICollection;
        if (is3 != null)
        {
            return is3.Count;
        }
        int num = 0;
        using (IEnumerator enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                num++;
            }
        }
        return num;
    }
    

提交回复
热议问题