What are the key differences between IEnumerable Count() and Length?
What are the key differences between IEnumerable Count() and Length ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By calling Count on
IEnumerable<T>I’m assuming you’re referring to the extension methodCountonSystem.Linq.Enumerable.Lengthis not a method onIEnumerable<T>but rather a property on array types in .NET, such asint[].The difference is performance. The
Lengthproperty is guaranteed to be a O(1) operation. The complexity of theCountextension 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 aCountproperty. If none are available then it will enumerate all items and count them which has a complexity of O(N).For example
The value
e2is implemented as a C# iterator which does not support O(1) counting and hence the methodCountmust enumerate the entire collection to determine how long it is.