Select.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  12. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.select?view=net-9.0-pp#system-linq-asyncenumerable-select-2(system-collections-generic-iasyncenumerable((-0))-system-func((-0-1)))
  13. /// <summary>
  14. /// Projects each element of an async-enumerable sequence into a new form.
  15. /// </summary>
  16. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  17. /// <typeparam name="TResult">The type of the elements in the result sequence, obtained by running the selector function for each element in the source sequence.</typeparam>
  18. /// <param name="source">A sequence of elements to invoke a transform function on.</param>
  19. /// <param name="selector">A transform function to apply to each source element.</param>
  20. /// <returns>An async-enumerable sequence whose elements are the result of invoking the transform function on each element of source.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  22. public static IAsyncEnumerable<TResult> Select<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector)
  23. {
  24. if (source == null)
  25. throw Error.ArgumentNull(nameof(source));
  26. if (selector == null)
  27. throw Error.ArgumentNull(nameof(selector));
  28. return source switch
  29. {
  30. AsyncIterator<TSource> iterator => iterator.Select(selector),
  31. IList<TSource> list => new SelectIListIterator<TSource, TResult>(list, selector),
  32. _ => new SelectEnumerableAsyncIterator<TSource, TResult>(source, selector),
  33. };
  34. }
  35. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.select?view=net-9.0-pp#system-linq-asyncenumerable-select-2(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-int32-1)))
  36. /// <summary>
  37. /// Projects each element of an async-enumerable sequence into a new form by incorporating the element's index.
  38. /// </summary>
  39. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  40. /// <typeparam name="TResult">The type of the elements in the result sequence, obtained by running the selector function for each element in the source sequence.</typeparam>
  41. /// <param name="source">A sequence of elements to invoke a transform function on.</param>
  42. /// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
  43. /// <returns>An async-enumerable sequence whose elements are the result of invoking the transform function on each element of source.</returns>
  44. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  45. public static IAsyncEnumerable<TResult> Select<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, TResult> selector)
  46. {
  47. if (source == null)
  48. throw Error.ArgumentNull(nameof(source));
  49. if (selector == null)
  50. throw Error.ArgumentNull(nameof(selector));
  51. return Core(source, selector);
  52. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, TResult> selector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  53. {
  54. var index = -1;
  55. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  56. {
  57. checked
  58. {
  59. index++;
  60. }
  61. yield return selector(element, index);
  62. }
  63. }
  64. }
  65. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  66. /// <summary>
  67. /// Projects each element of an async-enumerable sequence into a new form by applying an asynchronous selector function to each member of the source sequence and awaiting the result.
  68. /// </summary>
  69. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  70. /// <typeparam name="TResult">The type of the elements in the result sequence, obtained by running the selector function for each element in the source sequence and awaiting the result.</typeparam>
  71. /// <param name="source">A sequence of elements to invoke a transform function on.</param>
  72. /// <param name="selector">An asynchronous transform function to apply to each source element.</param>
  73. /// <returns>An async-enumerable sequence whose elements are the result of invoking the transform function on each element of the source sequence and awaiting the result.</returns>
  74. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  75. [GenerateAsyncOverload]
  76. [Obsolete("Use Select. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the SelectAwait functionality now exists as overloads of Select.")]
  77. private static IAsyncEnumerable<TResult> SelectAwaitCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TResult>> selector)
  78. {
  79. if (source == null)
  80. throw Error.ArgumentNull(nameof(source));
  81. if (selector == null)
  82. throw Error.ArgumentNull(nameof(selector));
  83. return source switch
  84. {
  85. AsyncIterator<TSource> iterator => iterator.Select(selector),
  86. IList<TSource> list => new SelectIListIteratorWithTask<TSource, TResult>(list, selector),
  87. _ => new SelectEnumerableAsyncIteratorWithTask<TSource, TResult>(source, selector),
  88. };
  89. }
  90. #if !NO_DEEP_CANCELLATION
  91. [GenerateAsyncOverload]
  92. [Obsolete("Use Select. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the SelectAwaitWithCancellation functionality now exists as overloads of Select.")]
  93. private static IAsyncEnumerable<TResult> SelectAwaitWithCancellationCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector)
  94. {
  95. if (source == null)
  96. throw Error.ArgumentNull(nameof(source));
  97. if (selector == null)
  98. throw Error.ArgumentNull(nameof(selector));
  99. return source switch
  100. {
  101. AsyncIterator<TSource> iterator => iterator.Select(selector),
  102. IList<TSource> list => new SelectIListIteratorWithTaskAndCancellation<TSource, TResult>(list, selector),
  103. _ => new SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult>(source, selector),
  104. };
  105. }
  106. #endif
  107. /// <summary>
  108. /// Projects each element of an async-enumerable sequence into a new form by applying an asynchronous selector function that incorporates each element's index to each element of the source sequence and awaiting the result.
  109. /// </summary>
  110. /// <typeparam name="TSource">The type of elements in the source sequence.</typeparam>
  111. /// <typeparam name="TResult">The type of elements in the result sequence, obtained by running the selector function for each element and its index, and awaiting the result.</typeparam>
  112. /// <param name="source">A sequence of elements to invoke a transform function on.</param>
  113. /// <param name="selector">An asynchronous transform function to apply to each source element; the second parameter represents the index of the element.</param>
  114. /// <returns>An async-enumerable sequence whose elements are the result of invoking the transform function on each element and its index of the source sequence and awaiting the result.</returns>
  115. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  116. [GenerateAsyncOverload]
  117. [Obsolete("Use Select. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the SelectAwait functionality now exists as overloads of Select.")]
  118. private static IAsyncEnumerable<TResult> SelectAwaitCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, ValueTask<TResult>> selector)
  119. {
  120. if (source == null)
  121. throw Error.ArgumentNull(nameof(source));
  122. if (selector == null)
  123. throw Error.ArgumentNull(nameof(selector));
  124. return Core(source, selector);
  125. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, ValueTask<TResult>> selector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  126. {
  127. var index = -1;
  128. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  129. {
  130. checked
  131. {
  132. index++;
  133. }
  134. yield return await selector(element, index).ConfigureAwait(false);
  135. }
  136. }
  137. }
  138. #if !NO_DEEP_CANCELLATION
  139. [GenerateAsyncOverload]
  140. [Obsolete("Use Select. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the SelectAwaitWithCancellation functionality now exists as overloads of Select.")]
  141. private static IAsyncEnumerable<TResult> SelectAwaitWithCancellationCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, CancellationToken, ValueTask<TResult>> selector)
  142. {
  143. if (source == null)
  144. throw Error.ArgumentNull(nameof(source));
  145. if (selector == null)
  146. throw Error.ArgumentNull(nameof(selector));
  147. return Core(source, selector);
  148. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, int, CancellationToken, ValueTask<TResult>> selector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  149. {
  150. var index = -1;
  151. await foreach (var element in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  152. {
  153. checked
  154. {
  155. index++;
  156. }
  157. yield return await selector(element, index, cancellationToken).ConfigureAwait(false);
  158. }
  159. }
  160. }
  161. #endif
  162. internal sealed class SelectEnumerableAsyncIterator<TSource, TResult> : AsyncIterator<TResult>
  163. {
  164. private readonly Func<TSource, TResult> _selector;
  165. private readonly IAsyncEnumerable<TSource> _source;
  166. private IAsyncEnumerator<TSource>? _enumerator;
  167. public SelectEnumerableAsyncIterator(IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector)
  168. {
  169. _source = source;
  170. _selector = selector;
  171. }
  172. public override AsyncIteratorBase<TResult> Clone()
  173. {
  174. return new SelectEnumerableAsyncIterator<TSource, TResult>(_source, _selector);
  175. }
  176. public override async ValueTask DisposeAsync()
  177. {
  178. if (_enumerator != null)
  179. {
  180. await _enumerator.DisposeAsync().ConfigureAwait(false);
  181. _enumerator = null;
  182. }
  183. await base.DisposeAsync().ConfigureAwait(false);
  184. }
  185. public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, TResult1> selector)
  186. {
  187. return new SelectEnumerableAsyncIterator<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
  188. }
  189. protected override async ValueTask<bool> MoveNextCore()
  190. {
  191. switch (_state)
  192. {
  193. case AsyncIteratorState.Allocated:
  194. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  195. _state = AsyncIteratorState.Iterating;
  196. goto case AsyncIteratorState.Iterating;
  197. case AsyncIteratorState.Iterating:
  198. if (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  199. {
  200. _current = _selector(_enumerator.Current);
  201. return true;
  202. }
  203. break;
  204. }
  205. await DisposeAsync().ConfigureAwait(false);
  206. return false;
  207. }
  208. }
  209. internal sealed class SelectIListIterator<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>
  210. {
  211. private readonly Func<TSource, TResult> _selector;
  212. private readonly IList<TSource> _source;
  213. private IEnumerator<TSource>? _enumerator;
  214. public SelectIListIterator(IList<TSource> source, Func<TSource, TResult> selector)
  215. {
  216. _source = source;
  217. _selector = selector;
  218. }
  219. public override AsyncIteratorBase<TResult> Clone()
  220. {
  221. return new SelectIListIterator<TSource, TResult>(_source, _selector);
  222. }
  223. public override async ValueTask DisposeAsync()
  224. {
  225. if (_enumerator != null)
  226. {
  227. _enumerator.Dispose();
  228. _enumerator = null;
  229. }
  230. await base.DisposeAsync().ConfigureAwait(false);
  231. }
  232. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  233. {
  234. if (onlyIfCheap)
  235. {
  236. return new ValueTask<int>(-1);
  237. }
  238. cancellationToken.ThrowIfCancellationRequested();
  239. var count = 0;
  240. foreach (var item in _source)
  241. {
  242. _selector(item);
  243. checked
  244. {
  245. count++;
  246. }
  247. }
  248. return new ValueTask<int>(count);
  249. }
  250. public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, TResult1> selector)
  251. {
  252. return new SelectIListIterator<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
  253. }
  254. public ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  255. {
  256. cancellationToken.ThrowIfCancellationRequested();
  257. var n = _source.Count;
  258. var res = new TResult[n];
  259. for (var i = 0; i < n; i++)
  260. {
  261. res[i] = _selector(_source[i]);
  262. }
  263. return new ValueTask<TResult[]>(res);
  264. }
  265. public ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  266. {
  267. cancellationToken.ThrowIfCancellationRequested();
  268. var n = _source.Count;
  269. var res = new List<TResult>(n);
  270. for (var i = 0; i < n; i++)
  271. {
  272. res.Add(_selector(_source[i]));
  273. }
  274. return new ValueTask<List<TResult>>(res);
  275. }
  276. protected override async ValueTask<bool> MoveNextCore()
  277. {
  278. switch (_state)
  279. {
  280. case AsyncIteratorState.Allocated:
  281. _enumerator = _source.GetEnumerator();
  282. _state = AsyncIteratorState.Iterating;
  283. goto case AsyncIteratorState.Iterating;
  284. case AsyncIteratorState.Iterating:
  285. if (_enumerator!.MoveNext())
  286. {
  287. _current = _selector(_enumerator.Current);
  288. return true;
  289. }
  290. await DisposeAsync().ConfigureAwait(false);
  291. break;
  292. }
  293. return false;
  294. }
  295. }
  296. internal sealed class SelectEnumerableAsyncIteratorWithTask<TSource, TResult> : AsyncIterator<TResult>
  297. {
  298. private readonly Func<TSource, ValueTask<TResult>> _selector;
  299. private readonly IAsyncEnumerable<TSource> _source;
  300. private IAsyncEnumerator<TSource>? _enumerator;
  301. public SelectEnumerableAsyncIteratorWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TResult>> selector)
  302. {
  303. _source = source;
  304. _selector = selector;
  305. }
  306. public override AsyncIteratorBase<TResult> Clone()
  307. {
  308. return new SelectEnumerableAsyncIteratorWithTask<TSource, TResult>(_source, _selector);
  309. }
  310. public override async ValueTask DisposeAsync()
  311. {
  312. if (_enumerator != null)
  313. {
  314. await _enumerator.DisposeAsync().ConfigureAwait(false);
  315. _enumerator = null;
  316. }
  317. await base.DisposeAsync().ConfigureAwait(false);
  318. }
  319. public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, ValueTask<TResult1>> selector)
  320. {
  321. return new SelectEnumerableAsyncIteratorWithTask<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
  322. }
  323. protected override async ValueTask<bool> MoveNextCore()
  324. {
  325. switch (_state)
  326. {
  327. case AsyncIteratorState.Allocated:
  328. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  329. _state = AsyncIteratorState.Iterating;
  330. goto case AsyncIteratorState.Iterating;
  331. case AsyncIteratorState.Iterating:
  332. if (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  333. {
  334. _current = await _selector(_enumerator.Current).ConfigureAwait(false);
  335. return true;
  336. }
  337. break;
  338. }
  339. await DisposeAsync().ConfigureAwait(false);
  340. return false;
  341. }
  342. }
  343. #if !NO_DEEP_CANCELLATION
  344. internal sealed class SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult> : AsyncIterator<TResult>
  345. {
  346. private readonly Func<TSource, CancellationToken, ValueTask<TResult>> _selector;
  347. private readonly IAsyncEnumerable<TSource> _source;
  348. private IAsyncEnumerator<TSource>? _enumerator;
  349. public SelectEnumerableAsyncIteratorWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector)
  350. {
  351. _source = source;
  352. _selector = selector;
  353. }
  354. public override AsyncIteratorBase<TResult> Clone()
  355. {
  356. return new SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult>(_source, _selector);
  357. }
  358. public override async ValueTask DisposeAsync()
  359. {
  360. if (_enumerator != null)
  361. {
  362. await _enumerator.DisposeAsync().ConfigureAwait(false);
  363. _enumerator = null;
  364. }
  365. await base.DisposeAsync().ConfigureAwait(false);
  366. }
  367. public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, CancellationToken, ValueTask<TResult1>> selector)
  368. {
  369. return new SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
  370. }
  371. protected override async ValueTask<bool> MoveNextCore()
  372. {
  373. switch (_state)
  374. {
  375. case AsyncIteratorState.Allocated:
  376. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  377. _state = AsyncIteratorState.Iterating;
  378. goto case AsyncIteratorState.Iterating;
  379. case AsyncIteratorState.Iterating:
  380. if (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  381. {
  382. _current = await _selector(_enumerator.Current, _cancellationToken).ConfigureAwait(false);
  383. return true;
  384. }
  385. break;
  386. }
  387. await DisposeAsync().ConfigureAwait(false);
  388. return false;
  389. }
  390. }
  391. #endif
  392. // NB: LINQ to Objects implements IPartition<TResult> for this. However, it seems incorrect to do so in a trivial
  393. // manner where e.g. TryGetLast simply indexes into the list without running the selector for the first n - 1
  394. // elements in order to ensure side-effects. We should consider whether we want to follow this implementation
  395. // strategy or support IAsyncPartition<TResult> in a less efficient but more correct manner here.
  396. private sealed class SelectIListIteratorWithTask<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>
  397. {
  398. private readonly Func<TSource, ValueTask<TResult>> _selector;
  399. private readonly IList<TSource> _source;
  400. private IEnumerator<TSource>? _enumerator;
  401. public SelectIListIteratorWithTask(IList<TSource> source, Func<TSource, ValueTask<TResult>> selector)
  402. {
  403. _source = source;
  404. _selector = selector;
  405. }
  406. public override AsyncIteratorBase<TResult> Clone()
  407. {
  408. return new SelectIListIteratorWithTask<TSource, TResult>(_source, _selector);
  409. }
  410. public override async ValueTask DisposeAsync()
  411. {
  412. if (_enumerator != null)
  413. {
  414. _enumerator.Dispose();
  415. _enumerator = null;
  416. }
  417. await base.DisposeAsync().ConfigureAwait(false);
  418. }
  419. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  420. {
  421. if (onlyIfCheap)
  422. {
  423. return new ValueTask<int>(-1);
  424. }
  425. return Core();
  426. async ValueTask<int> Core()
  427. {
  428. cancellationToken.ThrowIfCancellationRequested();
  429. var count = 0;
  430. foreach (var item in _source)
  431. {
  432. await _selector(item).ConfigureAwait(false);
  433. checked
  434. {
  435. count++;
  436. }
  437. }
  438. return count;
  439. }
  440. }
  441. public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, ValueTask<TResult1>> selector)
  442. {
  443. return new SelectIListIteratorWithTask<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
  444. }
  445. public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  446. {
  447. cancellationToken.ThrowIfCancellationRequested();
  448. var n = _source.Count;
  449. var res = new TResult[n];
  450. for (var i = 0; i < n; i++)
  451. {
  452. res[i] = await _selector(_source[i]).ConfigureAwait(false);
  453. }
  454. return res;
  455. }
  456. public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  457. {
  458. cancellationToken.ThrowIfCancellationRequested();
  459. var n = _source.Count;
  460. var res = new List<TResult>(n);
  461. for (var i = 0; i < n; i++)
  462. {
  463. res.Add(await _selector(_source[i]).ConfigureAwait(false));
  464. }
  465. return res;
  466. }
  467. protected override async ValueTask<bool> MoveNextCore()
  468. {
  469. switch (_state)
  470. {
  471. case AsyncIteratorState.Allocated:
  472. _enumerator = _source.GetEnumerator();
  473. _state = AsyncIteratorState.Iterating;
  474. goto case AsyncIteratorState.Iterating;
  475. case AsyncIteratorState.Iterating:
  476. if (_enumerator!.MoveNext())
  477. {
  478. _current = await _selector(_enumerator.Current).ConfigureAwait(false);
  479. return true;
  480. }
  481. break;
  482. }
  483. await DisposeAsync().ConfigureAwait(false);
  484. return false;
  485. }
  486. }
  487. #if !NO_DEEP_CANCELLATION
  488. private sealed class SelectIListIteratorWithTaskAndCancellation<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>
  489. {
  490. private readonly Func<TSource, CancellationToken, ValueTask<TResult>> _selector;
  491. private readonly IList<TSource> _source;
  492. private IEnumerator<TSource>? _enumerator;
  493. public SelectIListIteratorWithTaskAndCancellation(IList<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector)
  494. {
  495. _source = source;
  496. _selector = selector;
  497. }
  498. public override AsyncIteratorBase<TResult> Clone()
  499. {
  500. return new SelectIListIteratorWithTaskAndCancellation<TSource, TResult>(_source, _selector);
  501. }
  502. public override async ValueTask DisposeAsync()
  503. {
  504. if (_enumerator != null)
  505. {
  506. _enumerator.Dispose();
  507. _enumerator = null;
  508. }
  509. await base.DisposeAsync().ConfigureAwait(false);
  510. }
  511. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  512. {
  513. if (onlyIfCheap)
  514. {
  515. return new ValueTask<int>(-1);
  516. }
  517. return Core();
  518. async ValueTask<int> Core()
  519. {
  520. cancellationToken.ThrowIfCancellationRequested();
  521. var count = 0;
  522. foreach (var item in _source)
  523. {
  524. await _selector(item, cancellationToken).ConfigureAwait(false);
  525. checked
  526. {
  527. count++;
  528. }
  529. }
  530. return count;
  531. }
  532. }
  533. public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, CancellationToken, ValueTask<TResult1>> selector)
  534. {
  535. return new SelectIListIteratorWithTaskAndCancellation<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
  536. }
  537. public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
  538. {
  539. cancellationToken.ThrowIfCancellationRequested();
  540. var n = _source.Count;
  541. var res = new TResult[n];
  542. for (var i = 0; i < n; i++)
  543. {
  544. res[i] = await _selector(_source[i], cancellationToken).ConfigureAwait(false);
  545. }
  546. return res;
  547. }
  548. public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
  549. {
  550. cancellationToken.ThrowIfCancellationRequested();
  551. var n = _source.Count;
  552. var res = new List<TResult>(n);
  553. for (var i = 0; i < n; i++)
  554. {
  555. res.Add(await _selector(_source[i], cancellationToken).ConfigureAwait(false));
  556. }
  557. return res;
  558. }
  559. protected override async ValueTask<bool> MoveNextCore()
  560. {
  561. switch (_state)
  562. {
  563. case AsyncIteratorState.Allocated:
  564. _enumerator = _source.GetEnumerator();
  565. _state = AsyncIteratorState.Iterating;
  566. goto case AsyncIteratorState.Iterating;
  567. case AsyncIteratorState.Iterating:
  568. if (_enumerator!.MoveNext())
  569. {
  570. _current = await _selector(_enumerator.Current, _cancellationToken).ConfigureAwait(false);
  571. return true;
  572. }
  573. break;
  574. }
  575. await DisposeAsync().ConfigureAwait(false);
  576. return false;
  577. }
  578. }
  579. #endif
  580. }
  581. }