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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With