Skip to content

Add IReadOnlyCollection<T> as a optimised path for LINQ methods (e.g. .Count()) #135266

Closed as duplicate

Description

@MikeBarker-MSFT

Description

Currently, LINQ has optimised paths for ICollection<TSource>, Iterator<TSource>, and ICollection in the .Count<TSource>(this IEnumerable<TSource>) extension method. These optimised paths can be further expanded to include the IReadOnlyCollection<T>.

Example: A minimal repro is:

using System.Collections;

var rocollection = new ReadOnlyCollection<int>([1, 2, 3, 4, 5]);
var count = rocollection.Count();
Console.WriteLine(count);
Console.WriteLine($"IsCountInvoked:{rocollection.IsCountInvoked}; IsGetEnumeratorInvoked:{rocollection.IsGetEnumeratorInvoked}");

class ReadOnlyCollection<T> : IReadOnlyCollection<T>
{
    private readonly List<T> _list;

    public ReadOnlyCollection(IEnumerable<T> enumerable)
    {
        this._list = new(enumerable);
    }

    public bool IsCountInvoked { get; private set; } = false;
    public bool IsGetEnumeratorInvoked { get; private set; } = false;

    public int Count
    {
        get
        {
            this.IsCountInvoked = true;
            return this._list.Count;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        this.IsGetEnumeratorInvoked = true;
        return this._list.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}

There are further locations in LINQ where a similar optimisation can be utilised.

Activity

  1. dotnet-policy-service commented on Oct 6, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

  2. huoyaoyuan commented on Oct 6, 2026

    @huoyaoyuan
    Member

    Duplicate of #42254

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions