Min.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. {
  21. if (!await e.MoveNextAsync())
  22. throw Error.NoElements();
  23. var min = e.Current;
  24. while (await e.MoveNextAsync())
  25. {
  26. var cur = e.Current;
  27. if (comparer.Compare(cur, min) < 0)
  28. {
  29. min = cur;
  30. }
  31. }
  32. return min;
  33. }
  34. }
  35. }
  36. }
  37. }