Skip to content

Clean-up: Reduce repeated checks for ICollection<T>.Count, Iterator.GetCount and ICollection.Count #135269

Description

@MikeBarker-MSFT

Within LINQ there are multiple places where the code adds optimised paths for the ICollection<T>, Iterator<T> and ICollection in order to get the Count of the source collection. These can be collapsed to utilise the Enumerable.TryGetNonEnumeratedCount method, reducing repeated code.

This clean-up task has the advantage that adding a new optimisation (say, for IReadOnlyCollection<T>) to TryGetNonEnumeratedCount would accrue to all users of this method.

Activity

  1. added
    untriaged
    on Oct 6, 2026
  2. 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.

  3. MikeBarker-MSFT commented on Oct 6, 2026

    @MikeBarker-MSFT
    Author

    Specific cases:

    • Enumerable.Any<TSource>(this IEnumerable<TSource>)
    • Enumerable.Count<TSource>(this IEnumerable<TSource>)
    • Enumerable.AppendPrepend1Iterator<TSource>.GetCount(bool onlyIfCheap)
    • Enumerable.AppendPrependN<TSource>.GetCount(bool onlyIfCheap)
    • Enumerable.DefaultIfEmptyIterator<TSource>.GetCount(bool onlyIfCheap)
    • Enumerable.OrderedIterator<TElement>.GetCount(bool onlyIfCheap)
  4. huoyaoyuan commented on Oct 6, 2026

    @huoyaoyuan
    Member

    #135270 (comment)

    These can be collapsed to utilise the Enumerable.TryGetNonEnumeratedCount method, reducing repeated code.

    This clean-up task has the advantage that adding a new optimisation (say, for IReadOnlyCollection<T>) to TryGetNonEnumeratedCount would accrue to all users of this method.

    For speed-optimized LINQ, it's not the goal to make code minimal. Generally, "clean-up" should not be performed without solid performance data. Different methods can employ the same series of checks, but optimized with different preferences.

  5. JakeYallop commented on Oct 6, 2026

    @JakeYallop
    Contributor

    I feel like there have been a few PRs in the past that have considered doing something like this, and there have been reasons given for why not to do it. For example, #99218 removed TryGetNonEnumeratedCount

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Collectionsuntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions