Min.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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> MinAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource> comparer)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return MinCore(source, comparer, CancellationToken.None);
  16. }
  17. public static Task<TSource> MinAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource> comparer, CancellationToken cancellationToken)
  18. {
  19. if (source == null)
  20. throw Error.ArgumentNull(nameof(source));
  21. return MinCore(source, comparer, cancellationToken);
  22. }
  23. private static async Task<TSource> MinCore<TSource>(IAsyncEnumerable<TSource> source, IComparer<TSource> comparer, CancellationToken cancellationToken)
  24. {
  25. if (comparer == null)
  26. {
  27. comparer = Comparer<TSource>.Default;
  28. }
  29. var e = source.GetAsyncEnumerator(cancellationToken);
  30. try
  31. {
  32. if (!await e.MoveNextAsync().ConfigureAwait(false))
  33. throw Error.NoElements();
  34. var min = e.Current;
  35. while (await e.MoveNextAsync().ConfigureAwait(false))
  36. {
  37. var cur = e.Current;
  38. if (comparer.Compare(cur, min) < 0)
  39. {
  40. min = cur;
  41. }
  42. }
  43. return min;
  44. }
  45. finally
  46. {
  47. await e.DisposeAsync().ConfigureAwait(false);
  48. }
  49. }
  50. }
  51. }