Max.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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> MaxAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource> comparer, CancellationToken cancellationToken = default)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return Core();
  16. async Task<TSource> Core()
  17. {
  18. if (comparer == null)
  19. {
  20. comparer = Comparer<TSource>.Default;
  21. }
  22. #if CSHARP8
  23. await using (var e = source.GetAsyncEnumerator(cancellationToken).ConfigureAwait(false))
  24. {
  25. if (!await e.MoveNextAsync())
  26. throw Error.NoElements();
  27. var max = e.Current;
  28. while (await e.MoveNextAsync())
  29. {
  30. var cur = e.Current;
  31. if (comparer.Compare(cur, max) > 0)
  32. {
  33. max = cur;
  34. }
  35. }
  36. return max;
  37. }
  38. #else
  39. var e = source.GetAsyncEnumerator(cancellationToken);
  40. try
  41. {
  42. if (!await e.MoveNextAsync().ConfigureAwait(false))
  43. throw Error.NoElements();
  44. var max = e.Current;
  45. while (await e.MoveNextAsync().ConfigureAwait(false))
  46. {
  47. var cur = e.Current;
  48. if (comparer.Compare(cur, max) > 0)
  49. {
  50. max = cur;
  51. }
  52. }
  53. return max;
  54. }
  55. finally
  56. {
  57. await e.DisposeAsync().ConfigureAwait(false);
  58. }
  59. #endif
  60. }
  61. }
  62. }
  63. }