Max.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.maxasync?view=net-9.0-pp
  13. // The method above has a slightly different signature: it takes a comparer. In cases where the cancellationToken
  14. // has not been supplied, or has been passed by name, that method is source-compatible with this one.
  15. // However, anyone calling this method with an unnamed cancellationToken argument will get an error because
  16. // the comparer argument comes before the cancellationToken argument. There's not much we can do about
  17. // this because if we continue to offer this method, it will result in ambiguous matches. The least bad
  18. // option seems to be to hide this method, and anyone who was relying on it taking a positional
  19. // cancellation token argument will need to deal with the compilation error.
  20. /// <summary>
  21. /// Returns the maximum element in an async-enumerable sequence.
  22. /// </summary>
  23. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  24. /// <param name="source">An async-enumerable sequence to determine the maximum element of.</param>
  25. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  26. /// <returns>A ValueTask containing a single element with the maximum element in the source sequence.</returns>
  27. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  28. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  29. public static ValueTask<TSource> MaxAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  30. {
  31. if (source == null)
  32. throw Error.ArgumentNull(nameof(source));
  33. if (default(TSource)! == null) // NB: Null value is desired; JIT-time check.
  34. {
  35. return Core(source, cancellationToken);
  36. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  37. {
  38. var comparer = Comparer<TSource>.Default;
  39. TSource value;
  40. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  41. {
  42. do
  43. {
  44. if (!await e.MoveNextAsync())
  45. {
  46. return default!;
  47. }
  48. value = e.Current;
  49. }
  50. while (value == null);
  51. while (await e.MoveNextAsync())
  52. {
  53. var x = e.Current;
  54. if (x != null && comparer.Compare(x, value) > 0)
  55. {
  56. value = x;
  57. }
  58. }
  59. }
  60. return value;
  61. }
  62. }
  63. else
  64. {
  65. return Core(source, cancellationToken);
  66. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  67. {
  68. var comparer = Comparer<TSource>.Default;
  69. TSource value;
  70. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  71. {
  72. if (!await e.MoveNextAsync())
  73. {
  74. throw Error.NoElements();
  75. }
  76. value = e.Current;
  77. while (await e.MoveNextAsync())
  78. {
  79. var x = e.Current;
  80. if (comparer.Compare(x, value) > 0)
  81. {
  82. value = x;
  83. }
  84. }
  85. }
  86. return value;
  87. }
  88. }
  89. }
  90. #endif
  91. /// <summary>
  92. /// Invokes a transform function on each element of a sequence and returns the maximum value.
  93. /// </summary>
  94. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  95. /// <typeparam name="TResult">The type of the objects derived from the elements in the source sequence to determine the maximum of.</typeparam>
  96. /// <param name="source">An async-enumerable sequence to determine the minimum element of.</param>
  97. /// <param name="selector">A transform function to apply to each element.</param>
  98. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  99. /// <returns>A ValueTask containing a single element with the value that corresponds to the maximum element in the source sequence.</returns>
  100. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  101. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  102. [Obsolete("Use MaxByAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the functionality previously provided by the MaxAsync overload that took a selector callback now exists as an overload of MaxByAsync.")]
  103. public static ValueTask<TResult> MaxAsync<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector, CancellationToken cancellationToken = default)
  104. {
  105. if (source == null)
  106. throw Error.ArgumentNull(nameof(source));
  107. if (selector == null)
  108. throw Error.ArgumentNull(nameof(selector));
  109. if (default(TResult)! == null) // NB: Null value is desired; JIT-time check.
  110. {
  111. return Core(source, selector, cancellationToken);
  112. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector, CancellationToken cancellationToken)
  113. {
  114. var comparer = Comparer<TResult>.Default;
  115. TResult value;
  116. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  117. {
  118. do
  119. {
  120. if (!await e.MoveNextAsync())
  121. {
  122. return default!;
  123. }
  124. value = selector(e.Current);
  125. }
  126. while (value == null);
  127. while (await e.MoveNextAsync())
  128. {
  129. var x = selector(e.Current);
  130. if (x != null && comparer.Compare(x, value) > 0)
  131. {
  132. value = x;
  133. }
  134. }
  135. }
  136. return value;
  137. }
  138. }
  139. else
  140. {
  141. return Core(source, selector, cancellationToken);
  142. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector, CancellationToken cancellationToken)
  143. {
  144. var comparer = Comparer<TResult>.Default;
  145. TResult value;
  146. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  147. {
  148. if (!await e.MoveNextAsync())
  149. {
  150. throw Error.NoElements();
  151. }
  152. value = selector(e.Current);
  153. while (await e.MoveNextAsync())
  154. {
  155. var x = selector(e.Current);
  156. if (comparer.Compare(x, value) > 0)
  157. {
  158. value = x;
  159. }
  160. }
  161. }
  162. return value;
  163. }
  164. }
  165. }
  166. /// <summary>
  167. /// Invokes and awaits a transform function on each element of a sequence and returns the maximum value.
  168. /// </summary>
  169. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  170. /// <typeparam name="TResult">The type of the objects derived from the elements in the source sequence to determine the maximum of.</typeparam>
  171. /// <param name="source">An async-enumerable sequence to determine the minimum element of.</param>
  172. /// <param name="selector">An asynchronous transform function to invoke and await on each element.</param>
  173. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  174. /// <returns>A ValueTask containing a single element with the value that corresponds to the maximum element in the source sequence.</returns>
  175. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is null.</exception>
  176. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  177. [GenerateAsyncOverload]
  178. [Obsolete("Use MaxByAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the functionality previously provided by MaxAwaitAsync now exists as an overload of MaxByAsync.")]
  179. private static ValueTask<TResult> MaxAwaitAsyncCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TResult>> selector, CancellationToken cancellationToken = default)
  180. {
  181. if (source == null)
  182. throw Error.ArgumentNull(nameof(source));
  183. if (selector == null)
  184. throw Error.ArgumentNull(nameof(selector));
  185. if (default(TResult)! == null) // NB: Null value is desired; JIT-time check.
  186. {
  187. return Core(source, selector, cancellationToken);
  188. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TResult>> selector, CancellationToken cancellationToken)
  189. {
  190. var comparer = Comparer<TResult>.Default;
  191. TResult value;
  192. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  193. {
  194. do
  195. {
  196. if (!await e.MoveNextAsync())
  197. {
  198. return default!;
  199. }
  200. value = await selector(e.Current).ConfigureAwait(false);
  201. }
  202. while (value == null);
  203. while (await e.MoveNextAsync())
  204. {
  205. var x = await selector(e.Current).ConfigureAwait(false);
  206. if (x != null && comparer.Compare(x, value) > 0)
  207. {
  208. value = x;
  209. }
  210. }
  211. }
  212. return value;
  213. }
  214. }
  215. else
  216. {
  217. return Core(source, selector, cancellationToken);
  218. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TResult>> selector, CancellationToken cancellationToken)
  219. {
  220. var comparer = Comparer<TResult>.Default;
  221. TResult value;
  222. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  223. {
  224. if (!await e.MoveNextAsync())
  225. {
  226. throw Error.NoElements();
  227. }
  228. value = await selector(e.Current).ConfigureAwait(false);
  229. while (await e.MoveNextAsync())
  230. {
  231. var x = await selector(e.Current).ConfigureAwait(false);
  232. if (comparer.Compare(x, value) > 0)
  233. {
  234. value = x;
  235. }
  236. }
  237. }
  238. return value;
  239. }
  240. }
  241. }
  242. #if !NO_DEEP_CANCELLATION
  243. [GenerateAsyncOverload]
  244. [Obsolete("Use MaxByAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the functionality previously provided by MaxAwaitWithCancellationAsync now exists as an overload of MaxByAsync.")]
  245. private static ValueTask<TResult> MaxAwaitWithCancellationAsyncCore<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector, CancellationToken cancellationToken = default)
  246. {
  247. if (source == null)
  248. throw Error.ArgumentNull(nameof(source));
  249. if (selector == null)
  250. throw Error.ArgumentNull(nameof(selector));
  251. if (default(TResult)! == null) // NB: Null value is desired; JIT-time check.
  252. {
  253. return Core(source, selector, cancellationToken);
  254. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector, CancellationToken cancellationToken)
  255. {
  256. var comparer = Comparer<TResult>.Default;
  257. TResult value;
  258. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  259. {
  260. do
  261. {
  262. if (!await e.MoveNextAsync())
  263. {
  264. return default!;
  265. }
  266. value = await selector(e.Current, cancellationToken).ConfigureAwait(false);
  267. }
  268. while (value == null);
  269. while (await e.MoveNextAsync())
  270. {
  271. var x = await selector(e.Current, cancellationToken).ConfigureAwait(false);
  272. if (x != null && comparer.Compare(x, value) > 0)
  273. {
  274. value = x;
  275. }
  276. }
  277. }
  278. return value;
  279. }
  280. }
  281. else
  282. {
  283. return Core(source, selector, cancellationToken);
  284. static async ValueTask<TResult> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector, CancellationToken cancellationToken)
  285. {
  286. var comparer = Comparer<TResult>.Default;
  287. TResult value;
  288. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  289. {
  290. if (!await e.MoveNextAsync())
  291. {
  292. throw Error.NoElements();
  293. }
  294. value = await selector(e.Current, cancellationToken).ConfigureAwait(false);
  295. while (await e.MoveNextAsync())
  296. {
  297. var x = await selector(e.Current, cancellationToken).ConfigureAwait(false);
  298. if (comparer.Compare(x, value) > 0)
  299. {
  300. value = x;
  301. }
  302. }
  303. }
  304. return value;
  305. }
  306. }
  307. }
  308. #endif
  309. }
  310. }