What are the key differences between IEnumerable
Count()
and Length
?
C# – Difference between IEnumerable Count() and Length
cienumerablenet
Related Topic
- C# – Deep cloning objects
- C# – What are the correct version numbers for C#
- .net – the difference between IQueryable
and IEnumerable - .net – Difference between decimal, float and double in .NET
- C# – Difference Between Select and SelectMany
- C# – Calculate difference between two dates (number of days)
- C# – Returning IEnumerable
vs. IQueryable - C# – IEnumerable vs List – What to Use? How do they work
Best Answer
By calling Count on
IEnumerable<T>
I'm assuming you're referring to the extension methodCount
onSystem.Linq.Enumerable
.Length
is not a method onIEnumerable<T>
but rather a property on array types in .Net such asint[]
.The difference is performance. The
Length
property is guaranteed to be a O(1) operation. The complexity of theCount
extension method differs based on runtime type of the object. It will attempt to cast to several types which support O(1) length lookup likeICollection<T>
via aCount
property. If none are available then it will enumerate all items and count them which has a complexity of O(N).For example
The value
e2
is implemented as a C# iterator which does not support O(1) counting and hence the methodCount
must enumerate the entire collection to determine how long it is.