Max.cs 17 KB

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