Max.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 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. public static Task<TSource> Max<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource> comparer)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. if (comparer == null)
  16. throw new ArgumentNullException(nameof(comparer));
  17. return MaxCore(source, comparer, CancellationToken.None);
  18. }
  19. public static Task<TSource> Max<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource> comparer, CancellationToken cancellationToken)
  20. {
  21. if (source == null)
  22. throw new ArgumentNullException(nameof(source));
  23. if (comparer == null)
  24. throw new ArgumentNullException(nameof(comparer));
  25. return MaxCore(source, comparer, cancellationToken);
  26. }
  27. private static async Task<TSource> MaxCore<TSource>(IAsyncEnumerable<TSource> source, IComparer<TSource> comparer, CancellationToken cancellationToken)
  28. {
  29. var e = source.GetAsyncEnumerator(cancellationToken);
  30. try
  31. {
  32. if (!await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  33. throw new InvalidOperationException(Strings.NO_ELEMENTS);
  34. var max = e.Current;
  35. while (await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  36. {
  37. var cur = e.Current;
  38. if (comparer.Compare(cur, max) > 0)
  39. {
  40. max = cur;
  41. }
  42. }
  43. return max;
  44. }
  45. finally
  46. {
  47. await e.DisposeAsync().ConfigureAwait(false);
  48. }
  49. }
  50. }
  51. }