Min.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #if !REFERENCE_ASSEMBLY
  12. /// <summary>
  13. /// Returns the minimum element in an async-enumerable sequence according to the specified comparer.
  14. /// </summary>
  15. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  16. /// <param name="source">An async-enumerable sequence to determine the minimum element of.</param>
  17. /// <param name="comparer">Comparer used to compare elements.</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 minimum element in the source sequence.</returns>
  20. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="comparer"/> 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<TSource> MinAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken = default)
  23. {
  24. if (source == null)
  25. throw Error.ArgumentNull(nameof(source));
  26. return Core(source, comparer, cancellationToken);
  27. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken)
  28. {
  29. comparer ??= Comparer<TSource>.Default;
  30. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  31. if (!await e.MoveNextAsync())
  32. throw Error.NoElements();
  33. var min = e.Current;
  34. while (await e.MoveNextAsync())
  35. {
  36. var cur = e.Current;
  37. if (comparer.Compare(cur, min) < 0)
  38. {
  39. min = cur;
  40. }
  41. }
  42. return min;
  43. }
  44. }
  45. #endif
  46. }
  47. }