Min.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 ValueTask<TSource> MinAsync<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(source, comparer, cancellationToken);
  16. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken)
  17. {
  18. comparer ??= Comparer<TSource>.Default;
  19. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  20. if (!await e.MoveNextAsync())
  21. throw Error.NoElements();
  22. var min = e.Current;
  23. while (await e.MoveNextAsync())
  24. {
  25. var cur = e.Current;
  26. if (comparer.Compare(cur, min) < 0)
  27. {
  28. min = cur;
  29. }
  30. }
  31. return min;
  32. }
  33. }
  34. }
  35. }