Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

284
Views
Should Count() of an IEnumerable be avoided?

In general, I am using a List and then returning them as IEnumerable when I no longer need to update them.

However, I ran into an issue where I actually need to enumerate through them but first need to know the count.

Will IEnumerable enumerate every item and find the count (O(N)), or will it rely on List's Count property (O(1))?

Also, what if the IEnumerable is the result of a LINQ query?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Will IEnumerable enumerate every item and find the count (O(N)), or will it rely on List's Count property (O(1))?

It will use the Count property. Basically the implementation checks whether or not the object implements ICollection<T> or ICollection, and calls the relevant Count property if so. (The use of the non-generic ICollection was only introduced in .NET 4; in .NET 3.5 it only noticed ICollection<T>.)

It's only documented for ICollection<T>, however:

If the type of source implements ICollection<T>, that implementation is used to obtain the count of elements. Otherwise, this method determines the count.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!