Select.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TResult> Select<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector)
  13. {
  14. if (source == null)
  15. throw new ArgumentNullException(nameof(source));
  16. if (selector == null)
  17. throw new ArgumentNullException(nameof(selector));
  18. return CreateEnumerable(() =>
  19. {
  20. var e = source.GetEnumerator();
  21. var current = default(TResult);
  22. var cts = new CancellationTokenDisposable();
  23. var d = Disposable.Create(cts, e);
  24. return CreateEnumerator(
  25. async ct =>
  26. {
  27. if (await e.MoveNext(cts.Token)
  28. .ConfigureAwait(false))
  29. {
  30. current = selector(e.Current);
  31. return true;
  32. }
  33. return false;
  34. },
  35. () => current,
  36. d.Dispose,
  37. e
  38. );
  39. });
  40. }
  41. public static IAsyncEnumerable<TResult> Select<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, TResult> selector)
  42. {
  43. if (source == null)
  44. throw new ArgumentNullException(nameof(source));
  45. if (selector == null)
  46. throw new ArgumentNullException(nameof(selector));
  47. return CreateEnumerable(() =>
  48. {
  49. var e = source.GetEnumerator();
  50. var current = default(TResult);
  51. var index = 0;
  52. var cts = new CancellationTokenDisposable();
  53. var d = Disposable.Create(cts, e);
  54. return CreateEnumerator(
  55. async ct =>
  56. {
  57. if (await e.MoveNext(cts.Token)
  58. .ConfigureAwait(false))
  59. {
  60. current = selector(e.Current, checked(index++));
  61. return true;
  62. }
  63. return false;
  64. },
  65. () => current,
  66. d.Dispose,
  67. e
  68. );
  69. });
  70. }
  71. }
  72. }