Aggregate.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. /// Applies an accumulator function over an async-enumerable sequence, returning the result of the aggregation as a single element in the result sequence.
  13. /// For aggregation behavior with incremental intermediate results, see System.Interactive.Async.AsyncEnumerableEx.Scan{TSource}.
  14. /// </summary>
  15. /// <typeparam name="TSource">The type of the elements in the source sequence and the result of the aggregation.</typeparam>
  16. /// <param name="source">An async-enumerable sequence to aggregate over.</param>
  17. /// <param name="accumulator">An accumulator function to be invoked on each element.</param>
  18. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  19. /// <returns>An async-enumerable sequence containing a single element with the final accumulator value.</returns>
  20. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="accumulator"/> is null.</exception>
  21. /// <exception cref="InvalidOperationException">(Asynchronous) The source sequence is empty.</exception>
  22. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  23. public static ValueTask<TSource> AggregateAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, TSource> accumulator, CancellationToken cancellationToken = default)
  24. {
  25. if (source == null)
  26. throw Error.ArgumentNull(nameof(source));
  27. if (accumulator == null)
  28. throw Error.ArgumentNull(nameof(accumulator));
  29. return Core(source, accumulator, cancellationToken);
  30. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TSource, TSource> accumulator, CancellationToken cancellationToken)
  31. {
  32. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  33. if (!await e.MoveNextAsync())
  34. {
  35. throw Error.NoElements();
  36. }
  37. var acc = e.Current;
  38. while (await e.MoveNextAsync())
  39. {
  40. acc = accumulator(acc, e.Current);
  41. }
  42. return acc;
  43. }
  44. }
  45. internal static ValueTask<TSource> AggregateAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, ValueTask<TSource>> accumulator, CancellationToken cancellationToken = default)
  46. {
  47. if (source == null)
  48. throw Error.ArgumentNull(nameof(source));
  49. if (accumulator == null)
  50. throw Error.ArgumentNull(nameof(accumulator));
  51. return Core(source, accumulator, cancellationToken);
  52. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TSource, ValueTask<TSource>> accumulator, CancellationToken cancellationToken)
  53. {
  54. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  55. if (!await e.MoveNextAsync())
  56. {
  57. throw Error.NoElements();
  58. }
  59. var acc = e.Current;
  60. while (await e.MoveNextAsync())
  61. {
  62. acc = await accumulator(acc, e.Current).ConfigureAwait(false);
  63. }
  64. return acc;
  65. }
  66. }
  67. #if !NO_DEEP_CANCELLATION
  68. internal static ValueTask<TSource> AggregateAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, CancellationToken, ValueTask<TSource>> accumulator, CancellationToken cancellationToken = default)
  69. {
  70. if (source == null)
  71. throw Error.ArgumentNull(nameof(source));
  72. if (accumulator == null)
  73. throw Error.ArgumentNull(nameof(accumulator));
  74. return Core(source, accumulator, cancellationToken);
  75. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TSource, CancellationToken, ValueTask<TSource>> accumulator, CancellationToken cancellationToken)
  76. {
  77. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  78. if (!await e.MoveNextAsync())
  79. {
  80. throw Error.NoElements();
  81. }
  82. var acc = e.Current;
  83. while (await e.MoveNextAsync())
  84. {
  85. acc = await accumulator(acc, e.Current, cancellationToken).ConfigureAwait(false);
  86. }
  87. return acc;
  88. }
  89. }
  90. #endif
  91. /// <summary>
  92. /// Applies an accumulator function over an async-enumerable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
  93. /// For aggregation behavior with incremental intermediate results, see System.Interactive.Async.AsyncEnumerableEx.Scan{TSource, Accumulate}".
  94. /// </summary>
  95. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  96. /// <typeparam name="TAccumulate">The type of the result of the aggregation.</typeparam>
  97. /// <param name="source">An async-enumerable sequence to aggregate over.</param>
  98. /// <param name="seed">The initial accumulator value.</param>
  99. /// <param name="accumulator">An accumulator function to be invoked on each element.</param>
  100. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  101. /// <returns>An async-enumerable sequence containing a single element with the final accumulator value.</returns>
  102. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="accumulator"/> is null.</exception>
  103. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  104. public static ValueTask<TAccumulate> AggregateAsync<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, CancellationToken cancellationToken = default)
  105. {
  106. if (source == null)
  107. throw Error.ArgumentNull(nameof(source));
  108. if (accumulator == null)
  109. throw Error.ArgumentNull(nameof(accumulator));
  110. return Core(source, seed, accumulator, cancellationToken);
  111. static async ValueTask<TAccumulate> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, CancellationToken cancellationToken)
  112. {
  113. var acc = seed;
  114. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  115. {
  116. acc = accumulator(acc, item);
  117. }
  118. return acc;
  119. }
  120. }
  121. internal static ValueTask<TAccumulate> AggregateAwaitAsyncCore<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, ValueTask<TAccumulate>> accumulator, CancellationToken cancellationToken = default)
  122. {
  123. if (source == null)
  124. throw Error.ArgumentNull(nameof(source));
  125. if (accumulator == null)
  126. throw Error.ArgumentNull(nameof(accumulator));
  127. return Core(source, seed, accumulator, cancellationToken);
  128. static async ValueTask<TAccumulate> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, ValueTask<TAccumulate>> accumulator, CancellationToken cancellationToken)
  129. {
  130. var acc = seed;
  131. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  132. {
  133. acc = await accumulator(acc, item).ConfigureAwait(false);
  134. }
  135. return acc;
  136. }
  137. }
  138. #if !NO_DEEP_CANCELLATION
  139. internal static ValueTask<TAccumulate> AggregateAwaitWithCancellationAsyncCore<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, CancellationToken, ValueTask<TAccumulate>> accumulator, CancellationToken cancellationToken = default)
  140. {
  141. if (source == null)
  142. throw Error.ArgumentNull(nameof(source));
  143. if (accumulator == null)
  144. throw Error.ArgumentNull(nameof(accumulator));
  145. return Core(source, seed, accumulator, cancellationToken);
  146. static async ValueTask<TAccumulate> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, CancellationToken, ValueTask<TAccumulate>> accumulator, CancellationToken cancellationToken)
  147. {
  148. var acc = seed;
  149. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  150. {
  151. acc = await accumulator(acc, item, cancellationToken).ConfigureAwait(false);
  152. }
  153. return acc;
  154. }
  155. }
  156. #endif
  157. /// <summary>
  158. /// Applies an accumulator function over an async-enumerable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value,
  159. /// and the specified result selector function is used to select the result value.
  160. /// </summary>
  161. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  162. /// <typeparam name="TAccumulate">The type of the accumulator value.</typeparam>
  163. /// <typeparam name="TResult">The type of the resulting value.</typeparam>
  164. /// <param name="source">An async-enumerable sequence to aggregate over.</param>
  165. /// <param name="seed">The initial accumulator value.</param>
  166. /// <param name="accumulator">An accumulator function to be invoked on each element.</param>
  167. /// <param name="resultSelector">A function to transform the final accumulator value into the result value.</param>
  168. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  169. /// <returns>An async-enumerable sequence containing a single element with the final accumulator value.</returns>
  170. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="accumulator"/> or <paramref name="resultSelector"/> is null.</exception>
  171. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  172. public static ValueTask<TResult> AggregateAsync<TSource, TAccumulate, TResult>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, Func<TAccumulate, TResult> resultSelector, CancellationToken cancellationToken = default)
  173. {
  174. if (source == null)
  175. throw Error.ArgumentNull(nameof(source));
  176. if (accumulator == null)
  177. throw Error.ArgumentNull(nameof(accumulator));
  178. if (resultSelector == null)
  179. throw Error.ArgumentNull(nameof(resultSelector));
  180. return Core(source, seed, accumulator, resultSelector, cancellationToken);
  181. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, Func<TAccumulate, TResult> resultSelector, CancellationToken cancellationToken)
  182. {
  183. var acc = seed;
  184. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  185. {
  186. acc = accumulator(acc, item);
  187. }
  188. return resultSelector(acc);
  189. }
  190. }
  191. internal static ValueTask<TResult> AggregateAwaitAsyncCore<TSource, TAccumulate, TResult>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, ValueTask<TAccumulate>> accumulator, Func<TAccumulate, ValueTask<TResult>> resultSelector, CancellationToken cancellationToken = default)
  192. {
  193. if (source == null)
  194. throw Error.ArgumentNull(nameof(source));
  195. if (accumulator == null)
  196. throw Error.ArgumentNull(nameof(accumulator));
  197. if (resultSelector == null)
  198. throw Error.ArgumentNull(nameof(resultSelector));
  199. return Core(source, seed, accumulator, resultSelector, cancellationToken);
  200. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, ValueTask<TAccumulate>> accumulator, Func<TAccumulate, ValueTask<TResult>> resultSelector, CancellationToken cancellationToken)
  201. {
  202. var acc = seed;
  203. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  204. {
  205. acc = await accumulator(acc, item).ConfigureAwait(false);
  206. }
  207. return await resultSelector(acc).ConfigureAwait(false);
  208. }
  209. }
  210. #if !NO_DEEP_CANCELLATION
  211. internal static ValueTask<TResult> AggregateAwaitWithCancellationAsyncCore<TSource, TAccumulate, TResult>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, CancellationToken, ValueTask<TAccumulate>> accumulator, Func<TAccumulate, CancellationToken, ValueTask<TResult>> resultSelector, CancellationToken cancellationToken = default)
  212. {
  213. if (source == null)
  214. throw Error.ArgumentNull(nameof(source));
  215. if (accumulator == null)
  216. throw Error.ArgumentNull(nameof(accumulator));
  217. if (resultSelector == null)
  218. throw Error.ArgumentNull(nameof(resultSelector));
  219. return Core(source, seed, accumulator, resultSelector, cancellationToken);
  220. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, CancellationToken, ValueTask<TAccumulate>> accumulator, Func<TAccumulate, CancellationToken, ValueTask<TResult>> resultSelector, CancellationToken cancellationToken)
  221. {
  222. var acc = seed;
  223. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  224. {
  225. acc = await accumulator(acc, item, cancellationToken).ConfigureAwait(false);
  226. }
  227. return await resultSelector(acc, cancellationToken).ConfigureAwait(false);
  228. }
  229. }
  230. #endif
  231. }
  232. }