Max.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 maximum value in an async-enumerable sequence according to the specified comparer.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <param name="source">An async-enumerable sequence to determine the maximum element of.</param>
  16. /// <param name="comparer">Comparer used to compare elements.</param>
  17. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  18. /// <returns>An async-enumerable sequence containing a single element with the maximum element in the source sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="comparer"/> is null.</exception>
  20. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  21. public static ValueTask<TSource> MaxAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken = default)
  22. {
  23. if (source == null)
  24. throw Error.ArgumentNull(nameof(source));
  25. return Core(source, comparer, cancellationToken);
  26. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken)
  27. {
  28. comparer ??= Comparer<TSource>.Default;
  29. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  30. if (!await e.MoveNextAsync())
  31. throw Error.NoElements();
  32. var max = e.Current;
  33. while (await e.MoveNextAsync())
  34. {
  35. var cur = e.Current;
  36. if (comparer.Compare(cur, max) > 0)
  37. {
  38. max = cur;
  39. }
  40. }
  41. return max;
  42. }
  43. }
  44. }
  45. }