Min.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. if (_comparer == null)
  19. {
  20. _comparer = Comparer<TSource>.Default;
  21. }
  22. await using (var e = _source.GetConfiguredAsyncEnumerator(_cancellationToken, false))
  23. {
  24. if (!await e.MoveNextAsync())
  25. throw Error.NoElements();
  26. var min = e.Current;
  27. while (await e.MoveNextAsync())
  28. {
  29. var cur = e.Current;
  30. if (_comparer.Compare(cur, min) < 0)
  31. {
  32. min = cur;
  33. }
  34. }
  35. return min;
  36. }
  37. }
  38. }
  39. }
  40. }