Grouping.cs 21 KB

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