Min.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. var e = _source.GetConfiguredAsyncEnumerator(_cancellationToken, false);
  23. try // TODO: Switch to `await using` in preview 3 (https://github.com/dotnet/roslyn/pull/32731)
  24. {
  25. if (!await e.MoveNextAsync())
  26. throw Error.NoElements();
  27. var min = e.Current;
  28. while (await e.MoveNextAsync())
  29. {
  30. var cur = e.Current;
  31. if (_comparer.Compare(cur, min) < 0)
  32. {
  33. min = cur;
  34. }
  35. }
  36. return min;
  37. }
  38. finally
  39. {
  40. await e.DisposeAsync();
  41. }
  42. }
  43. }
  44. }
  45. }