| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494 | // Licensed to the .NET Foundation under one or more agreements.// The .NET Foundation licenses this file to you under the Apache 2.0 License.// See the LICENSE file in the project root for more information. using System.Collections;using System.Collections.Generic;using System.Diagnostics;using System.Threading;using System.Threading.Tasks;namespace System.Linq{    public static partial class AsyncEnumerable    {        public static IAsyncEnumerable<IAsyncGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (elementSelector == null)                throw new ArgumentNullException(nameof(elementSelector));            if (comparer == null)                throw new ArgumentNullException(nameof(comparer));            return new GroupedAsyncEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer);        }        public static IAsyncEnumerable<IAsyncGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (elementSelector == null)                throw new ArgumentNullException(nameof(elementSelector));            return source.GroupBy(keySelector, elementSelector, EqualityComparer<TKey>.Default);        }        public static IAsyncEnumerable<IAsyncGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (comparer == null)                throw new ArgumentNullException(nameof(comparer));            return new GroupedAsyncEnumerable<TSource, TKey>(source, keySelector, comparer);        }        public static IAsyncEnumerable<IAsyncGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            return new GroupedAsyncEnumerable<TSource, TKey>(source, keySelector, EqualityComparer<TKey>.Default);        }        public static IAsyncEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (elementSelector == null)                throw new ArgumentNullException(nameof(elementSelector));            if (resultSelector == null)                throw new ArgumentNullException(nameof(resultSelector));            if (comparer == null)                throw new ArgumentNullException(nameof(comparer));            return source.GroupBy(keySelector, elementSelector, comparer).Select(g => resultSelector(g.Key, g));        }        public static IAsyncEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (elementSelector == null)                throw new ArgumentNullException(nameof(elementSelector));            if (resultSelector == null)                throw new ArgumentNullException(nameof(resultSelector));            return source.GroupBy(keySelector, elementSelector, EqualityComparer<TKey>.Default).Select(g => resultSelector(g.Key, g));        }        public static IAsyncEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (resultSelector == null)                throw new ArgumentNullException(nameof(resultSelector));            if (comparer == null)                throw new ArgumentNullException(nameof(comparer));            return new GroupedResultAsyncEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, comparer);        }        public static IAsyncEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector)        {            if (source == null)                throw new ArgumentNullException(nameof(source));            if (keySelector == null)                throw new ArgumentNullException(nameof(keySelector));            if (resultSelector == null)                throw new ArgumentNullException(nameof(resultSelector));            return GroupBy(source, keySelector, resultSelector, EqualityComparer<TKey>.Default);        }        internal sealed class GroupedResultAsyncEnumerable<TSource, TKey, TResult> : AsyncIterator<TResult>, IIListProvider<TResult>        {            private readonly IAsyncEnumerable<TSource> source;            private readonly Func<TSource, TKey> keySelector;            private readonly Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector;            private readonly IEqualityComparer<TKey> comparer;            private Internal.Lookup<TKey, TSource> lookup;            private IEnumerator<TResult> enumerator;            public GroupedResultAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer)            {                Debug.Assert(source != null);                Debug.Assert(keySelector != null);                Debug.Assert(resultSelector != null);                Debug.Assert(comparer != null);                this.source = source;                this.keySelector = keySelector;                this.resultSelector = resultSelector;                this.comparer = comparer;            }            public override AsyncIterator<TResult> Clone()            {                return new GroupedResultAsyncEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, comparer);            }            public override async Task DisposeAsync()            {                if (enumerator != null)                {                    enumerator.Dispose();                    enumerator = null;                    lookup = null;                }                await base.DisposeAsync().ConfigureAwait(false);            }            protected override async Task<bool> MoveNextCore()            {                switch (state)                {                    case AsyncIteratorState.Allocated:                        lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer).ConfigureAwait(false);                        enumerator = lookup.ApplyResultSelector(resultSelector).GetEnumerator();                        state = AsyncIteratorState.Iterating;                        goto case AsyncIteratorState.Iterating;                    case AsyncIteratorState.Iterating:                        if (enumerator.MoveNext())                        {                            current = enumerator.Current;                            return true;                        }                        await DisposeAsync().ConfigureAwait(false);                        break;                }                return false;            }            public async Task<TResult[]> ToArrayAsync(CancellationToken cancellationToken)            {                var l = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);                return l.ToArray(resultSelector);            }            public async Task<List<TResult>> ToListAsync(CancellationToken cancellationToken)            {                var l = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);                return l.ToList(resultSelector);            }            public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)            {                if (onlyIfCheap)                {                    return -1;                }                var l = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);                return l.Count;            }        }        internal sealed class GroupedAsyncEnumerable<TSource, TKey, TElement> : AsyncIterator<IAsyncGrouping<TKey, TElement>>, IIListProvider<IAsyncGrouping<TKey, TElement>>        {            private readonly IAsyncEnumerable<TSource> source;            private readonly Func<TSource, TKey> keySelector;            private readonly Func<TSource, TElement> elementSelector;            private readonly IEqualityComparer<TKey> comparer;            private Internal.Lookup<TKey, TElement> lookup;            private IEnumerator<IGrouping<TKey, TElement>> enumerator;            public GroupedAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)            {                Debug.Assert(source != null);                Debug.Assert(keySelector != null);                Debug.Assert(elementSelector != null);                Debug.Assert(comparer != null);                this.source = source;                this.keySelector = keySelector;                this.elementSelector = elementSelector;                this.comparer = comparer;            }            public override AsyncIterator<IAsyncGrouping<TKey, TElement>> Clone()            {                return new GroupedAsyncEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer);            }            public override async Task DisposeAsync()            {                if (enumerator != null)                {                    enumerator.Dispose();                    enumerator = null;                    lookup = null;                }                await base.DisposeAsync().ConfigureAwait(false);            }            protected override async Task<bool> MoveNextCore()            {                switch (state)                {                    case AsyncIteratorState.Allocated:                        lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer).ConfigureAwait(false);                        enumerator = lookup.GetEnumerator();                        state = AsyncIteratorState.Iterating;                        goto case AsyncIteratorState.Iterating;                    case AsyncIteratorState.Iterating:                        if (enumerator.MoveNext())                        {                            current = (IAsyncGrouping<TKey, TElement>)enumerator.Current;                            return true;                        }                        await DisposeAsync().ConfigureAwait(false);                        break;                }                return false;            }                        public async Task<IAsyncGrouping<TKey, TElement>[]> ToArrayAsync(CancellationToken cancellationToken)            {                IIListProvider<IAsyncGrouping<TKey, TElement>> l = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);                return await l.ToArrayAsync(cancellationToken).ConfigureAwait(false);            }            public async Task<List<IAsyncGrouping<TKey, TElement>>> ToListAsync(CancellationToken cancellationToken)            {                IIListProvider<IAsyncGrouping<TKey, TElement>> l = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);                return await l.ToListAsync(cancellationToken).ConfigureAwait(false);            }            public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)            {                if (onlyIfCheap)                {                    return -1;                }                var l = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);                return l.Count;            }        }        internal sealed class GroupedAsyncEnumerable<TSource, TKey> : AsyncIterator<IAsyncGrouping<TKey, TSource>>, IIListProvider<IAsyncGrouping<TKey, TSource>>        {            private readonly IAsyncEnumerable<TSource> source;            private readonly Func<TSource, TKey> keySelector;            private readonly IEqualityComparer<TKey> comparer;            private Internal.Lookup<TKey, TSource> lookup;            private IEnumerator<IGrouping<TKey, TSource>> enumerator;            public GroupedAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)            {                Debug.Assert(source != null);                Debug.Assert(keySelector != null);                Debug.Assert(comparer != null);                this.source = source;                this.keySelector = keySelector;                this.comparer = comparer;            }            public override AsyncIterator<IAsyncGrouping<TKey, TSource>> Clone()            {                return new GroupedAsyncEnumerable<TSource, TKey>(source, keySelector, comparer);            }            public override async Task DisposeAsync()            {                if (enumerator != null)                {                    enumerator.Dispose();                    enumerator = null;                    lookup = null;                }                await base.DisposeAsync().ConfigureAwait(false);            }            protected override async Task<bool> MoveNextCore()            {                switch (state)                {                    case AsyncIteratorState.Allocated:                        lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer).ConfigureAwait(false);                        enumerator = lookup.GetEnumerator();                        state = AsyncIteratorState.Iterating;                        goto case AsyncIteratorState.Iterating;                    case AsyncIteratorState.Iterating:                        if (enumerator.MoveNext())                        {                            current = (IAsyncGrouping<TKey, TSource>)enumerator.Current;                            return true;                        }                        await DisposeAsync().ConfigureAwait(false);                        break;                }                return false;            }            public async Task<IAsyncGrouping<TKey, TSource>[]> ToArrayAsync(CancellationToken cancellationToken)            {                IIListProvider<IAsyncGrouping<TKey, TSource>> l = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);                return await l.ToArrayAsync(cancellationToken).ConfigureAwait(false);            }            public async Task<List<IAsyncGrouping<TKey, TSource>>> ToListAsync(CancellationToken cancellationToken)            {                IIListProvider<IAsyncGrouping<TKey, TSource>> l = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);                return await l.ToListAsync(cancellationToken).ConfigureAwait(false);            }            public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)            {                if (onlyIfCheap)                {                    return -1;                }                var l = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer).ConfigureAwait(false);                return l.Count;            }        }    }}// Note: The type here has to be internal as System.Linq has it's own public copy we're not usingnamespace System.Linq.Internal{    /// Adapted from System.Linq.Grouping from .NET Framework    /// Source: https://github.com/dotnet/corefx/blob/b90532bc97b07234a7d18073819d019645285f1c/src/System.Linq/src/System/Linq/Grouping.cs#L64    internal class Grouping<TKey, TElement> : IGrouping<TKey, TElement>, IList<TElement>, IAsyncGrouping<TKey, TElement>    {        internal int _count;        internal TElement[] _elements;        internal int _hashCode;        internal Grouping<TKey, TElement> _hashNext;        internal TKey _key;        internal Grouping<TKey, TElement> _next;        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();        public IEnumerator<TElement> GetEnumerator()        {            for (var i = 0; i < _count; i++)            {                yield return _elements[i];            }        }        // DDB195907: implement IGrouping<>.Key implicitly        // so that WPF binding works on this property.        public TKey Key => _key;        int ICollection<TElement>.Count => _count;        bool ICollection<TElement>.IsReadOnly => true;        void ICollection<TElement>.Add(TElement item)        {            throw new NotSupportedException(Strings.NOT_SUPPORTED);        }        void ICollection<TElement>.Clear()        {            throw new NotSupportedException(Strings.NOT_SUPPORTED);        }        bool ICollection<TElement>.Contains(TElement item)        {            return Array.IndexOf(_elements, item, 0, _count) >= 0;        }        void ICollection<TElement>.CopyTo(TElement[] array, int arrayIndex)        {            Array.Copy(_elements, 0, array, arrayIndex, _count);        }        bool ICollection<TElement>.Remove(TElement item)        {            throw new NotSupportedException(Strings.NOT_SUPPORTED);        }        int IList<TElement>.IndexOf(TElement item) => Array.IndexOf(_elements, item, 0, _count);        void IList<TElement>.Insert(int index, TElement item)        {            throw new NotSupportedException(Strings.NOT_SUPPORTED);        }        void IList<TElement>.RemoveAt(int index)        {            throw new NotSupportedException(Strings.NOT_SUPPORTED);        }        TElement IList<TElement>.this[int index]        {            get            {                if (index < 0 || index >= _count)                {                    throw new ArgumentOutOfRangeException(nameof(index));                }                return _elements[index];            }            set { throw new NotSupportedException(Strings.NOT_SUPPORTED); }        }        internal void Add(TElement element)        {            if (_elements.Length == _count)            {                Array.Resize(ref _elements, checked(_count*2));            }            _elements[_count] = element;            _count++;        }        internal void Trim()        {            if (_elements.Length != _count)            {                Array.Resize(ref _elements, _count);            }        }        IAsyncEnumerator<TElement> IAsyncEnumerable<TElement>.GetAsyncEnumerator()        {            return this.ToAsyncEnumerable().GetAsyncEnumerator();        }    }}
 |