Grouping.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Runtime.ExceptionServices;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace System.Linq
  11. {
  12. public static partial class AsyncEnumerable
  13. {
  14. 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)
  15. {
  16. if (source == null)
  17. throw new ArgumentNullException(nameof(source));
  18. if (keySelector == null)
  19. throw new ArgumentNullException(nameof(keySelector));
  20. if (elementSelector == null)
  21. throw new ArgumentNullException(nameof(elementSelector));
  22. if (comparer == null)
  23. throw new ArgumentNullException(nameof(comparer));
  24. return new GroupedAsyncEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer);
  25. }
  26. public static IAsyncEnumerable<IAsyncGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
  27. {
  28. if (source == null)
  29. throw new ArgumentNullException(nameof(source));
  30. if (keySelector == null)
  31. throw new ArgumentNullException(nameof(keySelector));
  32. if (elementSelector == null)
  33. throw new ArgumentNullException(nameof(elementSelector));
  34. return source.GroupBy(keySelector, elementSelector, EqualityComparer<TKey>.Default);
  35. }
  36. public static IAsyncEnumerable<IAsyncGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  37. {
  38. if (source == null)
  39. throw new ArgumentNullException(nameof(source));
  40. if (keySelector == null)
  41. throw new ArgumentNullException(nameof(keySelector));
  42. if (comparer == null)
  43. throw new ArgumentNullException(nameof(comparer));
  44. return new GroupedAsyncEnumerable<TSource, TKey>(source, keySelector, comparer);
  45. }
  46. public static IAsyncEnumerable<IAsyncGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  47. {
  48. if (source == null)
  49. throw new ArgumentNullException(nameof(source));
  50. if (keySelector == null)
  51. throw new ArgumentNullException(nameof(keySelector));
  52. return new GroupedAsyncEnumerable<TSource, TKey>(source, keySelector, EqualityComparer<TKey>.Default);
  53. }
  54. 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)
  55. {
  56. if (source == null)
  57. throw new ArgumentNullException(nameof(source));
  58. if (keySelector == null)
  59. throw new ArgumentNullException(nameof(keySelector));
  60. if (elementSelector == null)
  61. throw new ArgumentNullException(nameof(elementSelector));
  62. if (resultSelector == null)
  63. throw new ArgumentNullException(nameof(resultSelector));
  64. if (comparer == null)
  65. throw new ArgumentNullException(nameof(comparer));
  66. return source.GroupBy(keySelector, elementSelector, comparer)
  67. .Select(g => resultSelector(g.Key, g));
  68. }
  69. 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)
  70. {
  71. if (source == null)
  72. throw new ArgumentNullException(nameof(source));
  73. if (keySelector == null)
  74. throw new ArgumentNullException(nameof(keySelector));
  75. if (elementSelector == null)
  76. throw new ArgumentNullException(nameof(elementSelector));
  77. if (resultSelector == null)
  78. throw new ArgumentNullException(nameof(resultSelector));
  79. return source.GroupBy(keySelector, elementSelector, EqualityComparer<TKey>.Default)
  80. .Select(g => resultSelector(g.Key, g));
  81. }
  82. 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)
  83. {
  84. if (source == null)
  85. throw new ArgumentNullException(nameof(source));
  86. if (keySelector == null)
  87. throw new ArgumentNullException(nameof(keySelector));
  88. if (resultSelector == null)
  89. throw new ArgumentNullException(nameof(resultSelector));
  90. if (comparer == null)
  91. throw new ArgumentNullException(nameof(comparer));
  92. return new GroupedResultAsyncEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, comparer);
  93. }
  94. public static IAsyncEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector)
  95. {
  96. if (source == null)
  97. throw new ArgumentNullException(nameof(source));
  98. if (keySelector == null)
  99. throw new ArgumentNullException(nameof(keySelector));
  100. if (resultSelector == null)
  101. throw new ArgumentNullException(nameof(resultSelector));
  102. return GroupBy(source, keySelector, resultSelector, EqualityComparer<TKey>.Default);
  103. }
  104. internal sealed class GroupedResultAsyncEnumerable<TSource, TKey, TResult> : AsyncIterator<TResult>, IIListProvider<TResult>
  105. {
  106. private readonly IAsyncEnumerable<TSource> source;
  107. private readonly Func<TSource, TKey> keySelector;
  108. private readonly Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector;
  109. private readonly IEqualityComparer<TKey> comparer;
  110. private Internal.Lookup<TKey, TSource> lookup;
  111. private IEnumerator<TResult> enumerator;
  112. public GroupedResultAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
  113. {
  114. Debug.Assert(source != null);
  115. Debug.Assert(keySelector != null);
  116. Debug.Assert(resultSelector != null);
  117. Debug.Assert(comparer != null);
  118. this.source = source;
  119. this.keySelector = keySelector;
  120. this.resultSelector = resultSelector;
  121. this.comparer = comparer;
  122. }
  123. public override AsyncIterator<TResult> Clone()
  124. {
  125. return new GroupedResultAsyncEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, comparer);
  126. }
  127. public override void Dispose()
  128. {
  129. if (enumerator != null)
  130. {
  131. enumerator.Dispose();
  132. enumerator = null;
  133. lookup = null;
  134. }
  135. base.Dispose();
  136. }
  137. protected override async Task<bool> MoveNextCore(CancellationToken cancellationToken)
  138. {
  139. switch (state)
  140. {
  141. case AsyncIteratorState.Allocated:
  142. lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  143. enumerator = lookup.ApplyResultSelector(resultSelector).GetEnumerator();
  144. state = AsyncIteratorState.Iterating;
  145. goto case AsyncIteratorState.Iterating;
  146. case AsyncIteratorState.Iterating:
  147. if (enumerator.MoveNext())
  148. {
  149. current = enumerator.Current;
  150. return true;
  151. }
  152. Dispose();
  153. break;
  154. }
  155. return false;
  156. }
  157. public async Task<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  158. {
  159. var lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  160. return lookup.ToArray(resultSelector);
  161. }
  162. public async Task<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  163. {
  164. var lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  165. return lookup.ToList(resultSelector);
  166. }
  167. public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  168. {
  169. if (onlyIfCheap)
  170. {
  171. return -1;
  172. }
  173. var lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  174. return lookup.Count;
  175. }
  176. }
  177. internal sealed class GroupedAsyncEnumerable<TSource, TKey, TElement> : AsyncIterator<IAsyncGrouping<TKey, TElement>>, IIListProvider<IAsyncGrouping<TKey, TElement>>
  178. {
  179. private readonly IAsyncEnumerable<TSource> source;
  180. private readonly Func<TSource, TKey> keySelector;
  181. private readonly Func<TSource, TElement> elementSelector;
  182. private readonly IEqualityComparer<TKey> comparer;
  183. private Internal.Lookup<TKey, TElement> lookup;
  184. private IEnumerator<IGrouping<TKey, TElement>> enumerator;
  185. public GroupedAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
  186. {
  187. Debug.Assert(source != null);
  188. Debug.Assert(keySelector != null);
  189. Debug.Assert(elementSelector != null);
  190. Debug.Assert(comparer != null);
  191. this.source = source;
  192. this.keySelector = keySelector;
  193. this.elementSelector = elementSelector;
  194. this.comparer = comparer;
  195. }
  196. public override AsyncIterator<IAsyncGrouping<TKey, TElement>> Clone()
  197. {
  198. return new GroupedAsyncEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer);
  199. }
  200. public override void Dispose()
  201. {
  202. if (enumerator != null)
  203. {
  204. enumerator.Dispose();
  205. enumerator = null;
  206. lookup = null;
  207. }
  208. base.Dispose();
  209. }
  210. protected override async Task<bool> MoveNextCore(CancellationToken cancellationToken)
  211. {
  212. switch (state)
  213. {
  214. case AsyncIteratorState.Allocated:
  215. lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);
  216. enumerator = lookup.GetEnumerator();
  217. state = AsyncIteratorState.Iterating;
  218. goto case AsyncIteratorState.Iterating;
  219. case AsyncIteratorState.Iterating:
  220. if (enumerator.MoveNext())
  221. {
  222. current = (IAsyncGrouping<TKey, TElement>)enumerator.Current;
  223. return true;
  224. }
  225. Dispose();
  226. break;
  227. }
  228. return false;
  229. }
  230. public async Task<IAsyncGrouping<TKey, TElement>[]> ToArrayAsync(CancellationToken cancellationToken)
  231. {
  232. IIListProvider<IAsyncGrouping<TKey, TElement>> lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);
  233. return await lookup.ToArrayAsync(cancellationToken).ConfigureAwait(false);
  234. }
  235. public async Task<List<IAsyncGrouping<TKey, TElement>>> ToListAsync(CancellationToken cancellationToken)
  236. {
  237. IIListProvider<IAsyncGrouping<TKey, TElement>> lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);
  238. return await lookup.ToListAsync(cancellationToken).ConfigureAwait(false);
  239. }
  240. public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  241. {
  242. if (onlyIfCheap)
  243. {
  244. return -1;
  245. }
  246. var lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer, cancellationToken).ConfigureAwait(false);
  247. return lookup.Count;
  248. }
  249. }
  250. internal sealed class GroupedAsyncEnumerable<TSource, TKey> : AsyncIterator<IAsyncGrouping<TKey, TSource>>, IIListProvider<IAsyncGrouping<TKey, TSource>>
  251. {
  252. private readonly IAsyncEnumerable<TSource> source;
  253. private readonly Func<TSource, TKey> keySelector;
  254. private readonly IEqualityComparer<TKey> comparer;
  255. private Internal.Lookup<TKey, TSource> lookup;
  256. private IEnumerator<IGrouping<TKey, TSource>> enumerator;
  257. public GroupedAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  258. {
  259. Debug.Assert(source != null);
  260. Debug.Assert(keySelector != null);
  261. Debug.Assert(comparer != null);
  262. this.source = source;
  263. this.keySelector = keySelector;
  264. this.comparer = comparer;
  265. }
  266. public override AsyncIterator<IAsyncGrouping<TKey, TSource>> Clone()
  267. {
  268. return new GroupedAsyncEnumerable<TSource, TKey>(source, keySelector, comparer);
  269. }
  270. public override void Dispose()
  271. {
  272. if (enumerator != null)
  273. {
  274. enumerator.Dispose();
  275. enumerator = null;
  276. lookup = null;
  277. }
  278. base.Dispose();
  279. }
  280. protected override async Task<bool> MoveNextCore(CancellationToken cancellationToken)
  281. {
  282. switch (state)
  283. {
  284. case AsyncIteratorState.Allocated:
  285. lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  286. enumerator = lookup.GetEnumerator();
  287. state = AsyncIteratorState.Iterating;
  288. goto case AsyncIteratorState.Iterating;
  289. case AsyncIteratorState.Iterating:
  290. if (enumerator.MoveNext())
  291. {
  292. current = (IAsyncGrouping<TKey, TSource>)enumerator.Current;
  293. return true;
  294. }
  295. Dispose();
  296. break;
  297. }
  298. return false;
  299. }
  300. public async Task<IAsyncGrouping<TKey, TSource>[]> ToArrayAsync(CancellationToken cancellationToken)
  301. {
  302. IIListProvider<IAsyncGrouping<TKey, TSource>> lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  303. return await lookup.ToArrayAsync(cancellationToken).ConfigureAwait(false);
  304. }
  305. public async Task<List<IAsyncGrouping<TKey, TSource>>> ToListAsync(CancellationToken cancellationToken)
  306. {
  307. IIListProvider<IAsyncGrouping<TKey, TSource>> lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  308. return await lookup.ToListAsync(cancellationToken).ConfigureAwait(false);
  309. }
  310. public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  311. {
  312. if (onlyIfCheap)
  313. {
  314. return -1;
  315. }
  316. var lookup = await Internal.Lookup<TKey, TSource>.CreateAsync(source, keySelector, comparer, cancellationToken).ConfigureAwait(false);
  317. return lookup.Count;
  318. }
  319. }
  320. }
  321. }
  322. // Note: The type here has to be internal as System.Linq has it's own public copy we're not using
  323. namespace System.Linq.Internal
  324. {
  325. /// Adapted from System.Linq.Grouping from .NET Framework
  326. /// Source: https://github.com/dotnet/corefx/blob/b90532bc97b07234a7d18073819d019645285f1c/src/System.Linq/src/System/Linq/Grouping.cs#L64
  327. internal class Grouping<TKey, TElement> : IGrouping<TKey, TElement>, IList<TElement>, IAsyncGrouping<TKey, TElement>
  328. {
  329. internal int _count;
  330. internal TElement[] _elements;
  331. internal int _hashCode;
  332. internal Grouping<TKey, TElement> _hashNext;
  333. internal TKey _key;
  334. internal Grouping<TKey, TElement> _next;
  335. IEnumerator IEnumerable.GetEnumerator()
  336. {
  337. return GetEnumerator();
  338. }
  339. public IEnumerator<TElement> GetEnumerator()
  340. {
  341. for (var i = 0; i < _count; i++)
  342. {
  343. yield return _elements[i];
  344. }
  345. }
  346. // DDB195907: implement IGrouping<>.Key implicitly
  347. // so that WPF binding works on this property.
  348. public TKey Key
  349. {
  350. get { return _key; }
  351. }
  352. int ICollection<TElement>.Count
  353. {
  354. get { return _count; }
  355. }
  356. bool ICollection<TElement>.IsReadOnly
  357. {
  358. get { return true; }
  359. }
  360. void ICollection<TElement>.Add(TElement item)
  361. {
  362. throw new NotSupportedException(Strings.NOT_SUPPORTED);
  363. }
  364. void ICollection<TElement>.Clear()
  365. {
  366. throw new NotSupportedException(Strings.NOT_SUPPORTED);
  367. }
  368. bool ICollection<TElement>.Contains(TElement item)
  369. {
  370. return Array.IndexOf(_elements, item, 0, _count) >= 0;
  371. }
  372. void ICollection<TElement>.CopyTo(TElement[] array, int arrayIndex)
  373. {
  374. Array.Copy(_elements, 0, array, arrayIndex, _count);
  375. }
  376. bool ICollection<TElement>.Remove(TElement item)
  377. {
  378. throw new NotSupportedException(Strings.NOT_SUPPORTED);
  379. }
  380. int IList<TElement>.IndexOf(TElement item)
  381. {
  382. return Array.IndexOf(_elements, item, 0, _count);
  383. }
  384. void IList<TElement>.Insert(int index, TElement item)
  385. {
  386. throw new NotSupportedException(Strings.NOT_SUPPORTED);
  387. }
  388. void IList<TElement>.RemoveAt(int index)
  389. {
  390. throw new NotSupportedException(Strings.NOT_SUPPORTED);
  391. }
  392. TElement IList<TElement>.this[int index]
  393. {
  394. get
  395. {
  396. if (index < 0 || index >= _count)
  397. {
  398. throw new ArgumentOutOfRangeException(nameof(index));
  399. }
  400. return _elements[index];
  401. }
  402. set { throw new NotSupportedException(Strings.NOT_SUPPORTED); }
  403. }
  404. internal void Add(TElement element)
  405. {
  406. if (_elements.Length == _count)
  407. {
  408. Array.Resize(ref _elements, checked(_count*2));
  409. }
  410. _elements[_count] = element;
  411. _count++;
  412. }
  413. internal void Trim()
  414. {
  415. if (_elements.Length != _count)
  416. {
  417. Array.Resize(ref _elements, _count);
  418. }
  419. }
  420. IAsyncEnumerator<TElement> IAsyncEnumerable<TElement>.GetEnumerator()
  421. {
  422. return this.ToAsyncEnumerable().GetEnumerator();
  423. }
  424. }
  425. }