MinBy.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 AsyncEnumerableEx
  10. {
  11. /// <summary>
  12. /// Returns the elements in an async-enumerable sequence with the minimum key value.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <typeparam name="TKey">The type of the key computed for each element in the source sequence.</typeparam>
  16. /// <param name="source">An async-enumerable sequence to get the minimum elements for.</param>
  17. /// <param name="keySelector">Key selector function.</param>
  18. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  19. /// <returns>A ValueTask containing a list of zero or more elements that have a minimum key value.</returns>
  20. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="keySelector"/> is null.</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<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, CancellationToken cancellationToken = default)
  23. {
  24. if (source == null)
  25. throw Error.ArgumentNull(nameof(source));
  26. if (keySelector == null)
  27. throw Error.ArgumentNull(nameof(keySelector));
  28. return MinByCore(source, keySelector, comparer: null, cancellationToken);
  29. }
  30. /// <summary>
  31. /// Returns the elements in an async-enumerable sequence with the minimum key value according to the specified comparer.
  32. /// </summary>
  33. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  34. /// <typeparam name="TKey">The type of the key computed for each element in the source sequence.</typeparam>
  35. /// <param name="source">An async-enumerable sequence to get the minimum elements for.</param>
  36. /// <param name="keySelector">Key selector function.</param>
  37. /// <param name="comparer">Comparer used to compare key values.</param>
  38. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  39. /// <returns>A ValueTask containing a list of zero or more elements that have a minimum key value.</returns>
  40. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="keySelector"/> or <paramref name="comparer"/> is null.</exception>
  41. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  42. public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default)
  43. {
  44. if (source == null)
  45. throw Error.ArgumentNull(nameof(source));
  46. if (keySelector == null)
  47. throw Error.ArgumentNull(nameof(keySelector));
  48. return MinByCore(source, keySelector, comparer, cancellationToken);
  49. }
  50. /// <summary>
  51. /// Returns the elements in an async-enumerable sequence with the minimum key value.
  52. /// </summary>
  53. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  54. /// <typeparam name="TKey">The type of the key computed for each element in the source sequence.</typeparam>
  55. /// <param name="source">An async-enumerable sequence to get the minimum elements for.</param>
  56. /// <param name="keySelector">Key selector function returning a key possibly asynchronously.</param>
  57. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  58. /// <returns>A ValueTask containing a list of zero or more elements that have a minimum key value.</returns>
  59. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="keySelector"/> is null.</exception>
  60. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  61. public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, CancellationToken cancellationToken = default)
  62. {
  63. if (source == null)
  64. throw Error.ArgumentNull(nameof(source));
  65. if (keySelector == null)
  66. throw Error.ArgumentNull(nameof(keySelector));
  67. return MinByCore<TSource, TKey>(source, keySelector, comparer: null, cancellationToken);
  68. }
  69. #if !NO_DEEP_CANCELLATION
  70. /// <summary>
  71. /// Returns the elements in an async-enumerable sequence with the minimum key value.
  72. /// </summary>
  73. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  74. /// <typeparam name="TKey">The type of the key computed for each element in the source sequence.</typeparam>
  75. /// <param name="source">An async-enumerable sequence to get the minimum elements for.</param>
  76. /// <param name="keySelector">Key selector function returning a key possibly asynchronously and supporting cancellation.</param>
  77. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  78. /// <returns>A ValueTask containing a list of zero or more elements that have a minimum key value.</returns>
  79. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="keySelector"/> is null.</exception>
  80. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  81. public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, CancellationToken cancellationToken = default)
  82. {
  83. if (source == null)
  84. throw Error.ArgumentNull(nameof(source));
  85. if (keySelector == null)
  86. throw Error.ArgumentNull(nameof(keySelector));
  87. return MinByCore<TSource, TKey>(source, keySelector, comparer: null, cancellationToken);
  88. }
  89. #endif
  90. /// <summary>
  91. /// Returns the elements in an async-enumerable sequence with the minimum key value according to the specified comparer.
  92. /// </summary>
  93. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  94. /// <typeparam name="TKey">The type of the key computed for each element in the source sequence.</typeparam>
  95. /// <param name="source">An async-enumerable sequence to get the minimum elements for.</param>
  96. /// <param name="keySelector">Key selector function returning a key possibly asynchronously.</param>
  97. /// <param name="comparer">Comparer used to compare key values.</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 list of zero or more elements that have a minimum key value.</returns>
  100. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="keySelector"/> or <paramref name="comparer"/> 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. public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default)
  103. {
  104. if (source == null)
  105. throw Error.ArgumentNull(nameof(source));
  106. if (keySelector == null)
  107. throw Error.ArgumentNull(nameof(keySelector));
  108. return MinByCore(source, keySelector, comparer, cancellationToken);
  109. }
  110. #if !NO_DEEP_CANCELLATION
  111. /// <summary>
  112. /// Returns the elements in an async-enumerable sequence with the minimum key value according to the specified comparer.
  113. /// </summary>
  114. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  115. /// <typeparam name="TKey">The type of the key computed for each element in the source sequence.</typeparam>
  116. /// <param name="source">An async-enumerable sequence to get the minimum elements for.</param>
  117. /// <param name="keySelector">Key selector function returning a key possibly asynchronously and supporting cancellation.</param>
  118. /// <param name="comparer">Comparer used to compare key values.</param>
  119. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  120. /// <returns>A ValueTask containing a list of zero or more elements that have a minimum key value.</returns>
  121. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="keySelector"/> or <paramref name="comparer"/> is null.</exception>
  122. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  123. public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, CancellationToken cancellationToken = default)
  124. {
  125. if (source == null)
  126. throw Error.ArgumentNull(nameof(source));
  127. if (keySelector == null)
  128. throw Error.ArgumentNull(nameof(keySelector));
  129. return MinByCore(source, keySelector, comparer, cancellationToken);
  130. }
  131. #endif
  132. private static ValueTask<IList<TSource>> MinByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
  133. {
  134. comparer ??= Comparer<TKey>.Default;
  135. return ExtremaBy(source, keySelector, (key, minValue) => -comparer.Compare(key, minValue), cancellationToken);
  136. }
  137. private static ValueTask<IList<TSource>> MinByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
  138. {
  139. comparer ??= Comparer<TKey>.Default;
  140. return ExtremaBy(source, keySelector, (key, minValue) => -comparer.Compare(key, minValue), cancellationToken);
  141. }
  142. #if !NO_DEEP_CANCELLATION
  143. private static ValueTask<IList<TSource>> MinByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
  144. {
  145. comparer ??= Comparer<TKey>.Default;
  146. return ExtremaBy(source, keySelector, (key, minValue) => -comparer.Compare(key, minValue), cancellationToken);
  147. }
  148. #endif
  149. private static async ValueTask<IList<TSource>> ExtremaBy<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, TKey, int> compare, CancellationToken cancellationToken)
  150. {
  151. var result = new List<TSource>();
  152. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  153. {
  154. if (!await e.MoveNextAsync())
  155. throw Error.NoElements();
  156. var current = e.Current;
  157. var resKey = keySelector(current);
  158. result.Add(current);
  159. while (await e.MoveNextAsync())
  160. {
  161. var cur = e.Current;
  162. var key = keySelector(cur);
  163. var cmp = compare(key, resKey);
  164. if (cmp == 0)
  165. {
  166. result.Add(cur);
  167. }
  168. else if (cmp > 0)
  169. {
  170. result = new List<TSource> { cur };
  171. resKey = key;
  172. }
  173. }
  174. }
  175. return result;
  176. }
  177. private static async ValueTask<IList<TSource>> ExtremaBy<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, Func<TKey, TKey, int> compare, CancellationToken cancellationToken)
  178. {
  179. var result = new List<TSource>();
  180. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  181. {
  182. if (!await e.MoveNextAsync())
  183. throw Error.NoElements();
  184. var current = e.Current;
  185. var resKey = await keySelector(current).ConfigureAwait(false);
  186. result.Add(current);
  187. while (await e.MoveNextAsync())
  188. {
  189. var cur = e.Current;
  190. var key = await keySelector(cur).ConfigureAwait(false);
  191. var cmp = compare(key, resKey);
  192. if (cmp == 0)
  193. {
  194. result.Add(cur);
  195. }
  196. else if (cmp > 0)
  197. {
  198. result = new List<TSource> { cur };
  199. resKey = key;
  200. }
  201. }
  202. }
  203. return result;
  204. }
  205. #if !NO_DEEP_CANCELLATION
  206. private static async ValueTask<IList<TSource>> ExtremaBy<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, Func<TKey, TKey, int> compare, CancellationToken cancellationToken)
  207. {
  208. var result = new List<TSource>();
  209. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  210. {
  211. if (!await e.MoveNextAsync())
  212. throw Error.NoElements();
  213. var current = e.Current;
  214. var resKey = await keySelector(current, cancellationToken).ConfigureAwait(false);
  215. result.Add(current);
  216. while (await e.MoveNextAsync())
  217. {
  218. var cur = e.Current;
  219. var key = await keySelector(cur, cancellationToken).ConfigureAwait(false);
  220. var cmp = compare(key, resKey);
  221. if (cmp == 0)
  222. {
  223. result.Add(cur);
  224. }
  225. else if (cmp > 0)
  226. {
  227. result = new List<TSource> { cur };
  228. resKey = key;
  229. }
  230. }
  231. }
  232. return result;
  233. }
  234. #endif
  235. }
  236. }