Count.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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;
  5. using System.Collections.Generic;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. /// <summary>
  13. /// Returns an async-enumerable sequence containing an <see cref="int" /> that represents the total number of elements in an async-enumerable sequence.
  14. /// </summary>
  15. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  16. /// <param name="source">An async-enumerable sequence that contains elements to be counted.</param>
  17. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  18. /// <returns>An async-enumerable sequence containing a single element with the number of elements in the input sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. /// <exception cref="OverflowException">(Asynchronous) The number of elements in the source sequence is larger than <see cref="long.MaxValue"/>.</exception>
  21. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  22. public static ValueTask<int> CountAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  23. {
  24. if (source == null)
  25. throw Error.ArgumentNull(nameof(source));
  26. return source switch
  27. {
  28. ICollection<TSource> collection => new ValueTask<int>(collection.Count),
  29. IAsyncIListProvider<TSource> listProv => listProv.GetCountAsync(onlyIfCheap: false, cancellationToken),
  30. ICollection collection => new ValueTask<int>(collection.Count),
  31. _ => Core(source, cancellationToken),
  32. };
  33. static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  34. {
  35. var count = 0;
  36. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  37. {
  38. checked
  39. {
  40. count++;
  41. }
  42. }
  43. return count;
  44. }
  45. }
  46. /// <summary>
  47. /// Returns an async-enumerable sequence containing an <see cref="int" /> that represents how many elements in the specified async-enumerable sequence satisfy a condition.
  48. /// </summary>
  49. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  50. /// <param name="source">An async-enumerable sequence that contains elements to be counted.</param>
  51. /// <param name="predicate">A function to test each element for a condition.</param>
  52. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  53. /// <returns>An async-enumerable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function.</returns>
  54. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  55. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  56. public static ValueTask<int> CountAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
  57. {
  58. if (source == null)
  59. throw Error.ArgumentNull(nameof(source));
  60. if (predicate == null)
  61. throw Error.ArgumentNull(nameof(predicate));
  62. return Core(source, predicate, cancellationToken);
  63. static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  64. {
  65. var count = 0;
  66. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  67. {
  68. if (predicate(item))
  69. {
  70. checked
  71. {
  72. count++;
  73. }
  74. }
  75. }
  76. return count;
  77. }
  78. }
  79. /// <summary>
  80. /// Counts the elements in an async-enumerable sequence that satisfy a condition.
  81. /// </summary>
  82. /// <typeparam name="TSource">Type of elements in the source sequence.</typeparam>
  83. /// <param name="source">A sequence of elements to count.</param>
  84. /// <param name="predicate">An asynchronous predicate to apply to each element in the source sequence.</param>
  85. /// <param name="cancellationToken">An optional cancellation token for cancelling the sequence at any time.</param>
  86. /// <returns>A ValueTask containing the number of elements in the sequence that satisfy the predicate.</returns>
  87. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is <see langword="null"/>.</exception>
  88. [GenerateAsyncOverload]
  89. private static ValueTask<int> CountAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  90. {
  91. if (source == null)
  92. throw Error.ArgumentNull(nameof(source));
  93. if (predicate == null)
  94. throw Error.ArgumentNull(nameof(predicate));
  95. return Core(source, predicate, cancellationToken);
  96. static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  97. {
  98. var count = 0;
  99. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  100. {
  101. if (await predicate(item).ConfigureAwait(false))
  102. {
  103. checked
  104. {
  105. count++;
  106. }
  107. }
  108. }
  109. return count;
  110. }
  111. }
  112. #if !NO_DEEP_CANCELLATION
  113. [GenerateAsyncOverload]
  114. private static ValueTask<int> CountAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  115. {
  116. if (source == null)
  117. throw Error.ArgumentNull(nameof(source));
  118. if (predicate == null)
  119. throw Error.ArgumentNull(nameof(predicate));
  120. return Core(source, predicate, cancellationToken);
  121. static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  122. {
  123. var count = 0;
  124. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  125. {
  126. if (await predicate(item, cancellationToken).ConfigureAwait(false))
  127. {
  128. checked
  129. {
  130. count++;
  131. }
  132. }
  133. }
  134. return count;
  135. }
  136. }
  137. #endif
  138. }
  139. }