Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling Count on IEnumerable iterate the whole collection? [duplicate]

Consider the following code:

static IEnumerable<int> GetItems()
{
    return Enumerable.Range(1, 10000000).ToArray();  // or: .ToList();
}

static void Main()
{
    int count = GetItems().Count();
}

Will it iterate over all the 10 billion integers and count them one-by-one, or will it use the array's Length / list's Count properties?

like image 956
Johan Hirsch Avatar asked Dec 12 '25 02:12

Johan Hirsch


1 Answers

If the IEnumerable is an ICollection, it will return the Count property.

Here's the source code:

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null) throw Error.ArgumentNull("source");
    ICollection<TSource> collectionoft = source as ICollection<TSource>;
    if (collectionoft != null) return collectionoft.Count;
    ICollection collection = source as ICollection;
    if (collection != null) return collection.Count;
    int count = 0;
    using (IEnumerator<TSource> e = source.GetEnumerator())
    {
        checked
        {
            while (e.MoveNext()) count++;
        }
    }
    return count;
}

An array implements ICollection<T>, so it doesn't need to be enumerated.

like image 72
Jakub Lortz Avatar answered Dec 14 '25 15:12

Jakub Lortz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!