Single.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 AsyncEnumerable
  10. {
  11. /// <summary>
  12. /// Returns the only element of an async-enumerable sequence, and reports an exception if there is not exactly one element in the async-enumerable sequence.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <param name="source">Source async-enumerable sequence.</param>
  16. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  17. /// <returns>ValueTask containing the single element in the async-enumerable sequence.</returns>
  18. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  19. /// <exception cref="InvalidOperationException">(Asynchronous) The source sequence contains more than one element. -or- The source sequence is empty.</exception>
  20. public static ValueTask<TSource> SingleAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  21. {
  22. if (source == null)
  23. throw Error.ArgumentNull(nameof(source));
  24. return Core(source, cancellationToken);
  25. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  26. {
  27. if (source is IList<TSource> list)
  28. {
  29. return list.Count switch
  30. {
  31. 0 => throw Error.NoElements(),
  32. 1 => list[0],
  33. _ => throw Error.MoreThanOneElement(),
  34. };
  35. }
  36. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  37. if (!await e.MoveNextAsync())
  38. {
  39. throw Error.NoElements();
  40. }
  41. var result = e.Current;
  42. if (await e.MoveNextAsync())
  43. {
  44. throw Error.MoreThanOneElement();
  45. }
  46. return result;
  47. }
  48. }
  49. /// <summary>
  50. /// Returns the only element of an async-enumerable sequence that satisfies the condition in the predicate, and reports an exception if there is not exactly one element in the async-enumerable sequence.
  51. /// </summary>
  52. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  53. /// <param name="source">Source async-enumerable sequence.</param>
  54. /// <param name="predicate">A predicate function to evaluate for elements in the source sequence.</param>
  55. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  56. /// <returns>ValueTask containing the single element in the async-enumerable sequence that satisfies the condition in the predicate.</returns>
  57. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  58. /// <exception cref="InvalidOperationException">(Asynchronous) No element satisfies the condition in the predicate. -or- More than one element satisfies the condition in the predicate. -or- The source sequence is empty.</exception>
  59. public static ValueTask<TSource> SingleAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
  60. {
  61. if (source == null)
  62. throw Error.ArgumentNull(nameof(source));
  63. if (predicate == null)
  64. throw Error.ArgumentNull(nameof(predicate));
  65. return Core(source, predicate, cancellationToken);
  66. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  67. {
  68. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  69. {
  70. while (await e.MoveNextAsync())
  71. {
  72. var result = e.Current;
  73. if (predicate(result))
  74. {
  75. while (await e.MoveNextAsync())
  76. {
  77. if (predicate(e.Current))
  78. {
  79. throw Error.MoreThanOneElement();
  80. }
  81. }
  82. return result;
  83. }
  84. }
  85. }
  86. throw Error.NoElements();
  87. }
  88. }
  89. internal static ValueTask<TSource> SingleAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  90. {
  91. if (source == null)
  92. throw Error.ArgumentNull(nameof(source));
  93. if (predicate == null)
  94. throw Error.ArgumentNull(nameof(predicate));
  95. return Core(source, predicate, cancellationToken);
  96. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  97. {
  98. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  99. {
  100. while (await e.MoveNextAsync())
  101. {
  102. var result = e.Current;
  103. if (await predicate(result).ConfigureAwait(false))
  104. {
  105. while (await e.MoveNextAsync())
  106. {
  107. if (await predicate(e.Current).ConfigureAwait(false))
  108. {
  109. throw Error.MoreThanOneElement();
  110. }
  111. }
  112. return result;
  113. }
  114. }
  115. }
  116. throw Error.NoElements();
  117. }
  118. }
  119. #if !NO_DEEP_CANCELLATION
  120. internal static ValueTask<TSource> SingleAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  121. {
  122. if (source == null)
  123. throw Error.ArgumentNull(nameof(source));
  124. if (predicate == null)
  125. throw Error.ArgumentNull(nameof(predicate));
  126. return Core(source, predicate, cancellationToken);
  127. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  128. {
  129. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  130. {
  131. while (await e.MoveNextAsync())
  132. {
  133. var result = e.Current;
  134. if (await predicate(result, cancellationToken).ConfigureAwait(false))
  135. {
  136. while (await e.MoveNextAsync())
  137. {
  138. if (await predicate(e.Current, cancellationToken).ConfigureAwait(false))
  139. {
  140. throw Error.MoreThanOneElement();
  141. }
  142. }
  143. return result;
  144. }
  145. }
  146. }
  147. throw Error.NoElements();
  148. }
  149. }
  150. #endif
  151. }
  152. }