Skip to content

Unnecessary outer loop in CountBy #106110

@AlexRadch

Description

@AlexRadch

The implementation of the new CountBy adds an unnecessary outer loop through the dictionary elements.

foreach (KeyValuePair<TKey, int> countBy in BuildCountDictionary(enumerator, keySelector, keyComparer))
{
yield return countBy;
}

I think we can return created Dictionary enumerator:

        public static IEnumerable<KeyValuePair<TKey, int>> CountBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? keyComparer = null) where TKey : notnull
        {
            // Same code 
            return new CountByEnumerable<TSource, TKey>(source, keySelector, keyComparer);
        }

        private sealed class CountByEnumerable<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? keyComparer) : IEnumerable<KeyValuePair<TKey, int>> where TKey : notnull
        {
            public IEnumerator<KeyValuePair<TKey, int>> GetEnumerator()
            {
                using IEnumerator<TSource> enumerator = source.GetEnumerator();

                if (!enumerator.MoveNext())
                {
                    return Empty<KeyValuePair<TKey, int>>().GetEnumerator();
                }

                return BuildCountDictionary(enumerator, keySelector, keyComparer).GetEnumerator();
            }
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Linqin-prThere is an active PR which will close this issue when it is mergedneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsiderationtenet-performancePerformance related issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions