Single.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. /// <summary>
  90. /// Returns the only element of an async-enumerable sequence that satisfies the condition in the asynchronous predicate, and reports an exception if there is not exactly one element in the async-enumerable sequence that matches the predicate.
  91. /// </summary>
  92. /// <typeparam name="TSource">The type of elements in the source sequence.</typeparam>
  93. /// <param name="source">Source async-enumerable sequence.</param>
  94. /// <param name="predicate">An asynchronous predicate that will be applied to each element of the source sequence.</param>
  95. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  96. /// <returns>ValueTask containing the only element in the async-enumerable sequence that satisfies the condition in the asynchronous predicate.</returns>
  97. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  98. /// <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>
  99. [GenerateAsyncOverload]
  100. private static ValueTask<TSource> SingleAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  101. {
  102. if (source == null)
  103. throw Error.ArgumentNull(nameof(source));
  104. if (predicate == null)
  105. throw Error.ArgumentNull(nameof(predicate));
  106. return Core(source, predicate, cancellationToken);
  107. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  108. {
  109. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  110. {
  111. while (await e.MoveNextAsync())
  112. {
  113. var result = e.Current;
  114. if (await predicate(result).ConfigureAwait(false))
  115. {
  116. while (await e.MoveNextAsync())
  117. {
  118. if (await predicate(e.Current).ConfigureAwait(false))
  119. {
  120. throw Error.MoreThanOneElement();
  121. }
  122. }
  123. return result;
  124. }
  125. }
  126. }
  127. throw Error.NoElements();
  128. }
  129. }
  130. #if !NO_DEEP_CANCELLATION
  131. [GenerateAsyncOverload]
  132. private static ValueTask<TSource> SingleAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  133. {
  134. if (source == null)
  135. throw Error.ArgumentNull(nameof(source));
  136. if (predicate == null)
  137. throw Error.ArgumentNull(nameof(predicate));
  138. return Core(source, predicate, cancellationToken);
  139. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  140. {
  141. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  142. {
  143. while (await e.MoveNextAsync())
  144. {
  145. var result = e.Current;
  146. if (await predicate(result, cancellationToken).ConfigureAwait(false))
  147. {
  148. while (await e.MoveNextAsync())
  149. {
  150. if (await predicate(e.Current, cancellationToken).ConfigureAwait(false))
  151. {
  152. throw Error.MoreThanOneElement();
  153. }
  154. }
  155. return result;
  156. }
  157. }
  158. }
  159. throw Error.NoElements();
  160. }
  161. }
  162. #endif
  163. }
  164. }