Where.cs 3.7 KB

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