SelectMany.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. /// <summary>
  12. /// Projects each element of an async-enumerable sequence to an async-enumerable sequence and merges the resulting async-enumerable sequences into one async-enumerable sequence.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <typeparam name="TResult">The type of the elements in the projected inner sequences and the elements in the merged result sequence.</typeparam>
  16. /// <param name="source">An async-enumerable sequence of elements to project.</param>
  17. /// <param name="selector">A transform function to apply to each element.</param>
  18. /// <returns>An async-enumerable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  20. public static IAsyncEnumerable<TResult> SelectMany<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TResult>> selector)
  21. {
  22. if (source == null)
  23. throw Error.ArgumentNull(nameof(source));
  24. if (selector == null)
  25. throw Error.ArgumentNull(nameof(selector));
  26. return new SelectManyAsyncIterator<TSource, TResult>(source, selector);
  27. }
  28. // REVIEW: Should we keep these overloads that return ValueTask<IAsyncEnumerable<TResult>>? One could argue the selector is async twice.
  29. internal static IAsyncEnumerable<TResult> SelectManyAwaitCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<IAsyncEnumerable<TResult>>> selector)
  30. {
  31. if (source == null)
  32. throw Error.ArgumentNull(nameof(source));
  33. if (selector == null)
  34. throw Error.ArgumentNull(nameof(selector));
  35. return new SelectManyAsyncIteratorWithTask<TSource, TResult>(source, selector);
  36. }
  37. #if !NO_DEEP_CANCELLATION
  38. internal static IAsyncEnumerable<TResult> SelectManyAwaitWithCancellationCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TResult>>> selector)
  39. {
  40. if (source == null)
  41. throw Error.ArgumentNull(nameof(source));
  42. if (selector == null)
  43. throw Error.ArgumentNull(nameof(selector));
  44. return new SelectManyAsyncIteratorWithTaskAndCancellation<TSource, TResult>(source, selector);
  45. }
  46. #endif
  47. /// <summary>
  48. /// Projects each element of an async-enumerable sequence to an async-enumerable sequence by incorporating the element's index and merges the resulting async-enumerable sequences into one async-enumerable sequence.
  49. /// </summary>
  50. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  51. /// <typeparam name="TResult">The type of the elements in the projected inner sequences and the elements in the merged result sequence.</typeparam>
  52. /// <param name="source">An async-enumerable sequence of elements to project.</param>
  53. /// <param name="selector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
  54. /// <returns>An async-enumerable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
  55. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  56. public static IAsyncEnumerable<TResult> SelectMany<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, IAsyncEnumerable<TResult>> selector)
  57. {
  58. if (source == null)
  59. throw Error.ArgumentNull(nameof(source));
  60. if (selector == null)
  61. throw Error.ArgumentNull(nameof(selector));
  62. return Core(source, selector);
  63. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, IAsyncEnumerable<TResult>> selector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  64. {
  65. var index = -1;
  66. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  67. {
  68. checked
  69. {
  70. index++;
  71. }
  72. var inner = selector(element, index);
  73. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  74. {
  75. yield return subElement;
  76. }
  77. }
  78. }
  79. }
  80. internal static IAsyncEnumerable<TResult> SelectManyAwaitCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, ValueTask<IAsyncEnumerable<TResult>>> selector)
  81. {
  82. if (source == null)
  83. throw Error.ArgumentNull(nameof(source));
  84. if (selector == null)
  85. throw Error.ArgumentNull(nameof(selector));
  86. return Core(source, selector);
  87. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, ValueTask<IAsyncEnumerable<TResult>>> selector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  88. {
  89. var index = -1;
  90. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  91. {
  92. checked
  93. {
  94. index++;
  95. }
  96. var inner = await selector(element, index).ConfigureAwait(false);
  97. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  98. {
  99. yield return subElement;
  100. }
  101. }
  102. }
  103. }
  104. #if !NO_DEEP_CANCELLATION
  105. internal static IAsyncEnumerable<TResult> SelectManyAwaitWithCancellationCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, CancellationToken, ValueTask<IAsyncEnumerable<TResult>>> selector)
  106. {
  107. if (source == null)
  108. throw Error.ArgumentNull(nameof(source));
  109. if (selector == null)
  110. throw Error.ArgumentNull(nameof(selector));
  111. return Core(source, selector);
  112. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, CancellationToken, ValueTask<IAsyncEnumerable<TResult>>> selector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  113. {
  114. var index = -1;
  115. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  116. {
  117. checked
  118. {
  119. index++;
  120. }
  121. var inner = await selector(element, index, cancellationToken).ConfigureAwait(false);
  122. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  123. {
  124. yield return subElement;
  125. }
  126. }
  127. }
  128. }
  129. #endif
  130. /// <summary>
  131. /// Projects each element of an async-enumerable sequence to an async-enumerable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one async-enumerable sequence.
  132. /// </summary>
  133. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  134. /// <typeparam name="TCollection">The type of the elements in the projected intermediate sequences.</typeparam>
  135. /// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate sequence elements.</typeparam>
  136. /// <param name="source">An async-enumerable sequence of elements to project.</param>
  137. /// <param name="collectionSelector">A transform function to apply to each element.</param>
  138. /// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
  139. /// <returns>An async-enumerable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.</returns>
  140. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="collectionSelector"/> or <paramref name="resultSelector"/> is null.</exception>
  141. public static IAsyncEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
  142. {
  143. if (source == null)
  144. throw Error.ArgumentNull(nameof(source));
  145. if (collectionSelector == null)
  146. throw Error.ArgumentNull(nameof(collectionSelector));
  147. if (resultSelector == null)
  148. throw Error.ArgumentNull(nameof(resultSelector));
  149. return Core(source, collectionSelector, resultSelector);
  150. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  151. {
  152. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  153. {
  154. var inner = collectionSelector(element);
  155. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  156. {
  157. yield return resultSelector(element, subElement);
  158. }
  159. }
  160. }
  161. }
  162. internal static IAsyncEnumerable<TResult> SelectManyAwaitCore<TSource, TCollection, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, ValueTask<TResult>> resultSelector)
  163. {
  164. if (source == null)
  165. throw Error.ArgumentNull(nameof(source));
  166. if (collectionSelector == null)
  167. throw Error.ArgumentNull(nameof(collectionSelector));
  168. if (resultSelector == null)
  169. throw Error.ArgumentNull(nameof(resultSelector));
  170. return Core(source, collectionSelector, resultSelector);
  171. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, ValueTask<TResult>> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  172. {
  173. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  174. {
  175. var inner = await collectionSelector(element).ConfigureAwait(false);
  176. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  177. {
  178. yield return await resultSelector(element, subElement).ConfigureAwait(false);
  179. }
  180. }
  181. }
  182. }
  183. #if !NO_DEEP_CANCELLATION
  184. internal static IAsyncEnumerable<TResult> SelectManyAwaitWithCancellationCore<TSource, TCollection, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, CancellationToken, ValueTask<TResult>> resultSelector)
  185. {
  186. if (source == null)
  187. throw Error.ArgumentNull(nameof(source));
  188. if (collectionSelector == null)
  189. throw Error.ArgumentNull(nameof(collectionSelector));
  190. if (resultSelector == null)
  191. throw Error.ArgumentNull(nameof(resultSelector));
  192. return Core(source, collectionSelector, resultSelector);
  193. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, CancellationToken, ValueTask<TResult>> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  194. {
  195. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  196. {
  197. var inner = await collectionSelector(element, cancellationToken).ConfigureAwait(false);
  198. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  199. {
  200. yield return await resultSelector(element, subElement, cancellationToken).ConfigureAwait(false);
  201. }
  202. }
  203. }
  204. }
  205. #endif
  206. /// <summary>
  207. /// Projects each element of an async-enumerable sequence to an async-enumerable sequence by incorporating the element's index, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one async-enumerable sequence.
  208. /// </summary>
  209. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  210. /// <typeparam name="TCollection">The type of the elements in the projected intermediate sequences.</typeparam>
  211. /// <typeparam name="TResult">The type of the elements in the result sequence, obtained by using the selector to combine source sequence elements with their corresponding intermediate sequence elements.</typeparam>
  212. /// <param name="source">An async-enumerable sequence of elements to project.</param>
  213. /// <param name="collectionSelector">A transform function to apply to each element; the second parameter of the function represents the index of the source element.</param>
  214. /// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence; the second parameter of the function represents the index of the source element and the fourth parameter represents the index of the intermediate element.</param>
  215. /// <returns>An async-enumerable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.</returns>
  216. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="collectionSelector"/> or <paramref name="resultSelector"/> is null.</exception>
  217. public static IAsyncEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, IAsyncEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
  218. {
  219. if (source == null)
  220. throw Error.ArgumentNull(nameof(source));
  221. if (collectionSelector == null)
  222. throw Error.ArgumentNull(nameof(collectionSelector));
  223. if (resultSelector == null)
  224. throw Error.ArgumentNull(nameof(resultSelector));
  225. return Core(source, collectionSelector, resultSelector);
  226. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, IAsyncEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  227. {
  228. var index = -1;
  229. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  230. {
  231. checked
  232. {
  233. index++;
  234. }
  235. var inner = collectionSelector(element, index);
  236. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  237. {
  238. yield return resultSelector(element, subElement);
  239. }
  240. }
  241. }
  242. }
  243. internal static IAsyncEnumerable<TResult> SelectManyAwaitCore<TSource, TCollection, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, ValueTask<TResult>> resultSelector)
  244. {
  245. if (source == null)
  246. throw Error.ArgumentNull(nameof(source));
  247. if (collectionSelector == null)
  248. throw Error.ArgumentNull(nameof(collectionSelector));
  249. if (resultSelector == null)
  250. throw Error.ArgumentNull(nameof(resultSelector));
  251. return Core(source, collectionSelector, resultSelector);
  252. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, ValueTask<TResult>> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  253. {
  254. var index = -1;
  255. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  256. {
  257. checked
  258. {
  259. index++;
  260. }
  261. var inner = await collectionSelector(element, index).ConfigureAwait(false);
  262. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  263. {
  264. yield return await resultSelector(element, subElement).ConfigureAwait(false);
  265. }
  266. }
  267. }
  268. }
  269. #if !NO_DEEP_CANCELLATION
  270. internal static IAsyncEnumerable<TResult> SelectManyAwaitWithCancellationCore<TSource, TCollection, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, CancellationToken, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, CancellationToken, ValueTask<TResult>> resultSelector)
  271. {
  272. if (source == null)
  273. throw Error.ArgumentNull(nameof(source));
  274. if (collectionSelector == null)
  275. throw Error.ArgumentNull(nameof(collectionSelector));
  276. if (resultSelector == null)
  277. throw Error.ArgumentNull(nameof(resultSelector));
  278. return Core(source, collectionSelector, resultSelector);
  279. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, CancellationToken, ValueTask<IAsyncEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, CancellationToken, ValueTask<TResult>> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  280. {
  281. var index = -1;
  282. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  283. {
  284. checked
  285. {
  286. index++;
  287. }
  288. var inner = await collectionSelector(element, index, cancellationToken).ConfigureAwait(false);
  289. await foreach (var subElement in inner.WithCancellation(cancellationToken).ConfigureAwait(false))
  290. {
  291. yield return await resultSelector(element, subElement, cancellationToken).ConfigureAwait(false);
  292. }
  293. }
  294. }
  295. }
  296. #endif
  297. private sealed class SelectManyAsyncIterator<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>
  298. {
  299. private const int State_Source = 1;
  300. private const int State_Result = 2;
  301. private readonly Func<TSource, IAsyncEnumerable<TResult>> _selector;
  302. private readonly IAsyncEnumerable<TSource> _source;
  303. private int _mode;
  304. private IAsyncEnumerator<TResult>? _resultEnumerator;
  305. private IAsyncEnumerator<TSource>? _sourceEnumerator;
  306. public SelectManyAsyncIterator(IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TResult>> selector)
  307. {
  308. _source = source;
  309. _selector = selector;
  310. }
  311. public override AsyncIteratorBase<TResult> Clone()
  312. {
  313. return new SelectManyAsyncIterator<TSource, TResult>(_source, _selector);
  314. }
  315. public override async ValueTask DisposeAsync()
  316. {
  317. if (_resultEnumerator != null)
  318. {
  319. await _resultEnumerator.DisposeAsync().ConfigureAwait(false);
  320. _resultEnumerator = null;
  321. }
  322. if (_sourceEnumerator != null)
  323. {
  324. await _sourceEnumerator.DisposeAsync().ConfigureAwait(false);
  325. _sourceEnumerator = null;
  326. }
  327. await base.DisposeAsync().ConfigureAwait(false);
  328. }
  329. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  330. {
  331. if (onlyIfCheap)
  332. {
  333. return new ValueTask<int>(-1);
  334. }
  335. return Core(cancellationToken);
  336. async ValueTask<int> Core(CancellationToken cancellationToken)
  337. {
  338. var count = 0;
  339. await foreach (var element in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  340. {
  341. checked
  342. {
  343. count += await _selector(element).CountAsync().ConfigureAwait(false);
  344. }
  345. }
  346. return count;
  347. }
  348. }
  349. public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  350. {
  351. // REVIEW: Substitute for SparseArrayBuilder<T> logic once we have access to that.
  352. var list = await ToListAsync(cancellationToken).ConfigureAwait(false);
  353. return list.ToArray();
  354. }
  355. public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  356. {
  357. var list = new List<TResult>();
  358. await foreach (var element in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  359. {
  360. var items = _selector(element);
  361. await list.AddRangeAsync(items, cancellationToken).ConfigureAwait(false);
  362. }
  363. return list;
  364. }
  365. protected override async ValueTask<bool> MoveNextCore()
  366. {
  367. switch (_state)
  368. {
  369. case AsyncIteratorState.Allocated:
  370. _sourceEnumerator = _source.GetAsyncEnumerator(_cancellationToken);
  371. _mode = State_Source;
  372. _state = AsyncIteratorState.Iterating;
  373. goto case AsyncIteratorState.Iterating;
  374. case AsyncIteratorState.Iterating:
  375. switch (_mode)
  376. {
  377. case State_Source:
  378. if (await _sourceEnumerator!.MoveNextAsync().ConfigureAwait(false))
  379. {
  380. if (_resultEnumerator != null)
  381. {
  382. await _resultEnumerator.DisposeAsync().ConfigureAwait(false);
  383. }
  384. var inner = _selector(_sourceEnumerator.Current);
  385. _resultEnumerator = inner.GetAsyncEnumerator(_cancellationToken);
  386. _mode = State_Result;
  387. goto case State_Result;
  388. }
  389. break;
  390. case State_Result:
  391. if (await _resultEnumerator!.MoveNextAsync().ConfigureAwait(false))
  392. {
  393. _current = _resultEnumerator.Current;
  394. return true;
  395. }
  396. _mode = State_Source;
  397. goto case State_Source; // loop
  398. }
  399. break;
  400. }
  401. await DisposeAsync().ConfigureAwait(false);
  402. return false;
  403. }
  404. }
  405. private sealed class SelectManyAsyncIteratorWithTask<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>
  406. {
  407. private const int State_Source = 1;
  408. private const int State_Result = 2;
  409. private readonly Func<TSource, ValueTask<IAsyncEnumerable<TResult>>> _selector;
  410. private readonly IAsyncEnumerable<TSource> _source;
  411. private int _mode;
  412. private IAsyncEnumerator<TResult>? _resultEnumerator;
  413. private IAsyncEnumerator<TSource>? _sourceEnumerator;
  414. public SelectManyAsyncIteratorWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<IAsyncEnumerable<TResult>>> selector)
  415. {
  416. _source = source;
  417. _selector = selector;
  418. }
  419. public override AsyncIteratorBase<TResult> Clone()
  420. {
  421. return new SelectManyAsyncIteratorWithTask<TSource, TResult>(_source, _selector);
  422. }
  423. public override async ValueTask DisposeAsync()
  424. {
  425. if (_resultEnumerator != null)
  426. {
  427. await _resultEnumerator.DisposeAsync().ConfigureAwait(false);
  428. _resultEnumerator = null;
  429. }
  430. if (_sourceEnumerator != null)
  431. {
  432. await _sourceEnumerator.DisposeAsync().ConfigureAwait(false);
  433. _sourceEnumerator = null;
  434. }
  435. await base.DisposeAsync().ConfigureAwait(false);
  436. }
  437. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  438. {
  439. if (onlyIfCheap)
  440. {
  441. return new ValueTask<int>(-1);
  442. }
  443. return Core(cancellationToken);
  444. async ValueTask<int> Core(CancellationToken cancellationToken)
  445. {
  446. var count = 0;
  447. await foreach (var element in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  448. {
  449. var items = await _selector(element).ConfigureAwait(false);
  450. checked
  451. {
  452. count += await items.CountAsync().ConfigureAwait(false);
  453. }
  454. }
  455. return count;
  456. }
  457. }
  458. public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  459. {
  460. // REVIEW: Substitute for SparseArrayBuilder<T> logic once we have access to that.
  461. var list = await ToListAsync(cancellationToken).ConfigureAwait(false);
  462. return list.ToArray();
  463. }
  464. public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  465. {
  466. var list = new List<TResult>();
  467. await foreach (var element in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  468. {
  469. var items = await _selector(element).ConfigureAwait(false);
  470. await list.AddRangeAsync(items, cancellationToken).ConfigureAwait(false);
  471. }
  472. return list;
  473. }
  474. protected override async ValueTask<bool> MoveNextCore()
  475. {
  476. switch (_state)
  477. {
  478. case AsyncIteratorState.Allocated:
  479. _sourceEnumerator = _source.GetAsyncEnumerator(_cancellationToken);
  480. _mode = State_Source;
  481. _state = AsyncIteratorState.Iterating;
  482. goto case AsyncIteratorState.Iterating;
  483. case AsyncIteratorState.Iterating:
  484. switch (_mode)
  485. {
  486. case State_Source:
  487. if (await _sourceEnumerator!.MoveNextAsync().ConfigureAwait(false))
  488. {
  489. if (_resultEnumerator != null)
  490. {
  491. await _resultEnumerator.DisposeAsync().ConfigureAwait(false);
  492. }
  493. var inner = await _selector(_sourceEnumerator.Current).ConfigureAwait(false);
  494. _resultEnumerator = inner.GetAsyncEnumerator(_cancellationToken);
  495. _mode = State_Result;
  496. goto case State_Result;
  497. }
  498. break;
  499. case State_Result:
  500. if (await _resultEnumerator!.MoveNextAsync().ConfigureAwait(false))
  501. {
  502. _current = _resultEnumerator.Current;
  503. return true;
  504. }
  505. _mode = State_Source;
  506. goto case State_Source; // loop
  507. }
  508. break;
  509. }
  510. await DisposeAsync().ConfigureAwait(false);
  511. return false;
  512. }
  513. }
  514. #if !NO_DEEP_CANCELLATION
  515. private sealed class SelectManyAsyncIteratorWithTaskAndCancellation<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>
  516. {
  517. private const int State_Source = 1;
  518. private const int State_Result = 2;
  519. private readonly Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TResult>>> _selector;
  520. private readonly IAsyncEnumerable<TSource> _source;
  521. private int _mode;
  522. private IAsyncEnumerator<TResult>? _resultEnumerator;
  523. private IAsyncEnumerator<TSource>? _sourceEnumerator;
  524. public SelectManyAsyncIteratorWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TResult>>> selector)
  525. {
  526. _source = source;
  527. _selector = selector;
  528. }
  529. public override AsyncIteratorBase<TResult> Clone()
  530. {
  531. return new SelectManyAsyncIteratorWithTaskAndCancellation<TSource, TResult>(_source, _selector);
  532. }
  533. public override async ValueTask DisposeAsync()
  534. {
  535. if (_resultEnumerator != null)
  536. {
  537. await _resultEnumerator.DisposeAsync().ConfigureAwait(false);
  538. _resultEnumerator = null;
  539. }
  540. if (_sourceEnumerator != null)
  541. {
  542. await _sourceEnumerator.DisposeAsync().ConfigureAwait(false);
  543. _sourceEnumerator = null;
  544. }
  545. await base.DisposeAsync().ConfigureAwait(false);
  546. }
  547. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  548. {
  549. if (onlyIfCheap)
  550. {
  551. return new ValueTask<int>(-1);
  552. }
  553. return Core(cancellationToken);
  554. async ValueTask<int> Core(CancellationToken cancellationToken)
  555. {
  556. var count = 0;
  557. await foreach (var element in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  558. {
  559. var items = await _selector(element, cancellationToken).ConfigureAwait(false);
  560. checked
  561. {
  562. count += await items.CountAsync().ConfigureAwait(false);
  563. }
  564. }
  565. return count;
  566. }
  567. }
  568. public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  569. {
  570. // REVIEW: Substitute for SparseArrayBuilder<T> logic once we have access to that.
  571. var list = await ToListAsync(cancellationToken).ConfigureAwait(false);
  572. return list.ToArray();
  573. }
  574. public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  575. {
  576. var list = new List<TResult>();
  577. await foreach (var element in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  578. {
  579. var items = await _selector(element, cancellationToken).ConfigureAwait(false);
  580. await list.AddRangeAsync(items, cancellationToken).ConfigureAwait(false);
  581. }
  582. return list;
  583. }
  584. protected override async ValueTask<bool> MoveNextCore()
  585. {
  586. switch (_state)
  587. {
  588. case AsyncIteratorState.Allocated:
  589. _sourceEnumerator = _source.GetAsyncEnumerator(_cancellationToken);
  590. _mode = State_Source;
  591. _state = AsyncIteratorState.Iterating;
  592. goto case AsyncIteratorState.Iterating;
  593. case AsyncIteratorState.Iterating:
  594. switch (_mode)
  595. {
  596. case State_Source:
  597. if (await _sourceEnumerator!.MoveNextAsync().ConfigureAwait(false))
  598. {
  599. if (_resultEnumerator != null)
  600. {
  601. await _resultEnumerator.DisposeAsync().ConfigureAwait(false);
  602. }
  603. var inner = await _selector(_sourceEnumerator.Current, _cancellationToken).ConfigureAwait(false);
  604. _resultEnumerator = inner.GetAsyncEnumerator(_cancellationToken);
  605. _mode = State_Result;
  606. goto case State_Result;
  607. }
  608. break;
  609. case State_Result:
  610. if (await _resultEnumerator!.MoveNextAsync().ConfigureAwait(false))
  611. {
  612. _current = _resultEnumerator.Current;
  613. return true;
  614. }
  615. _mode = State_Source;
  616. goto case State_Source; // loop
  617. }
  618. break;
  619. }
  620. await DisposeAsync().ConfigureAwait(false);
  621. return false;
  622. }
  623. }
  624. #endif
  625. }
  626. }