Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

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.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 423523
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T19:11:19+00:00 2026-05-12T19:11:19+00:00

If the LINQ Count() extension method is invoked on an IEnumerable<T> that has a

  • 0

If the LINQ Count() extension method is invoked on an IEnumerable<T> that has a Count property (e.g. List<T>), does the Count() method look for that property and return it (rather than counting the items by enumerating them)? The following test code seems to indicate that it does:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace CountSpeedTest
{
    // Output:
    // List      - CLR : 0 ms
    // Enumerate - CLR : 10 ms
    // List      - Mine: 12 ms
    // Enumerate - Mine: 12 ms
    class Program
    {
        private const int Runs = 10;
        private const int Items = 1000000;

        static void Main(string[] args)
        {
            var total = new long[] {0, 0, 0, 0};
            for (int i = 0; i < Runs; ++i)
            {
                var items = Enumerable.Range(0, Items).Select(o => o.ToString()).ToList();
                var list = new List<string>(items);
                var enumerate = new Enumerate<string>(items);
                total[0] += TimeCount(list, c => c.Count());
                total[1] += TimeCount(enumerate, c => c.Count());
                total[2] += TimeCount(list, c => c.SlowCount());
                total[3] += TimeCount(enumerate, c => c.SlowCount());
            }
            Console.WriteLine(String.Format("List      - CLR : {0} ms", total[0] / Runs));
            Console.WriteLine(String.Format("Enumerate - CLR : {0} ms", total[1] / Runs));
            Console.WriteLine(String.Format("List      - Mine: {0} ms", total[2] / Runs));
            Console.WriteLine(String.Format("Enumerate - Mine: {0} ms", total[3] / Runs));
            Console.ReadKey(true);
        }

        private static long TimeCount<T>(IEnumerable<T> collection, Func<IEnumerable<T>, int> counter)
        {
            var stopwatch = Stopwatch.StartNew();
            var count = counter(collection);
            stopwatch.Stop();
            if (count != Items) throw new Exception("Incorrect Count");
            return stopwatch.ElapsedMilliseconds;
        }
    }

    public static class CountExtensions
    {
        // Performs a simple enumeration based count.
        public static int SlowCount<T>(this IEnumerable<T> items)
        {
            var i = 0;
            var enumerator = items.GetEnumerator();
            while (enumerator.MoveNext()) i++;
            return i;
        }
    }

    // Wraps an IEnumerable<T> to hide its Count property.
    public class Enumerate<T> : IEnumerable<T>
    {
        private readonly IEnumerable<T> collection;
        public Enumerate(IEnumerable<T> collection) { this.collection = collection; }

        public IEnumerator<T> GetEnumerator() { return collection.GetEnumerator(); }
        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    }
}

On a related note: how can a custom collection which implements IEnumerable<T> expose its own Count property in such a way that the CLR Count() extension method can take advantage of it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T19:11:19+00:00Added an answer on May 12, 2026 at 7:11 pm

    It doesn’t look for a Count property by name, but it does check whether it implements ICollection<T>, and then uses that type’s Count property. From the documentation:

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

    (Obviously this only applies to the overload which doesn’t take a predicate.)

    So, if you want to obtain the count efficiently, make sure you implement ICollection<T>.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm aware that .Count() is an extension method in LINQ, and that fundamentally it
Is the LINQ Count() method any faster or slower than List<>.Count or Array.Length ?
I've written a custom LINQ extension method that extends the TakeWhile() method to be
I have found an extension method that handles sorting and paging for LINQ .
Can anyone help me with a Count extension method for IEnumerable (non generic interface).
I'm trying to implement a LINQ-to-SQL extension method that will simply get a random
Is there a limit to the rows that IEnumerable.Count() (or IQueryable.Count()) using LINQ to
I was aware that the Count() method supplied by LINQ had an optimization whereby
Linq in general, has extensions methods(at IEnumerable) like Where, Select, OrderBy. But use another
Using LINQ to Entities with Entity Framework and C#: I have a method that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.