c# - Does calling Count on IEnumerable iterate the whole collection? -
this question has answer here:
consider following code:
static ienumerable<int> getitems() { return enumerable.range(1, 10000000).toarray(); // or: .tolist(); } static void main() { int count = getitems().count(); }
will iterate on 10 billion integers , count them one-by-one, or use array's length
/ list's count
properties?
if ienumerable
icollection
, return count
property.
here's source code:
public static int count<tsource>(this ienumerable<tsource> source) { if (source == null) throw error.argumentnull("source"); icollection<tsource> collectionoft = source icollection<tsource>; if (collectionoft != null) return collectionoft.count; icollection collection = source 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>
, doesn't need enumerated.
Comments
Post a Comment