Single.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. #if REFERENCE_ASSEMBLY
  10. public static partial class AsyncEnumerableDeprecated
  11. #else
  12. public static partial class AsyncEnumerable
  13. #endif
  14. {
  15. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  16. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.singleasync?view=net-9.0-pp#system-linq-asyncenumerable-singleasync-1(system-collections-generic-iasyncenumerable((-0))-system-threading-cancellationtoken)
  17. /// <summary>
  18. /// 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.
  19. /// </summary>
  20. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  21. /// <param name="source">Source async-enumerable sequence.</param>
  22. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  23. /// <returns>ValueTask containing the single element in the async-enumerable sequence.</returns>
  24. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  25. /// <exception cref="InvalidOperationException">(Asynchronous) The source sequence contains more than one element. -or- The source sequence is empty.</exception>
  26. public static ValueTask<TSource> SingleAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  27. {
  28. if (source == null)
  29. throw Error.ArgumentNull(nameof(source));
  30. return Core(source, cancellationToken);
  31. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  32. {
  33. if (source is IList<TSource> list)
  34. {
  35. return list.Count switch
  36. {
  37. 0 => throw Error.NoElements(),
  38. 1 => list[0],
  39. _ => throw Error.MoreThanOneElement(),
  40. };
  41. }
  42. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  43. if (!await e.MoveNextAsync())
  44. {
  45. throw Error.NoElements();
  46. }
  47. var result = e.Current;
  48. if (await e.MoveNextAsync())
  49. {
  50. throw Error.MoreThanOneElement();
  51. }
  52. return result;
  53. }
  54. }
  55. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.singleasync?view=net-9.0-pp#system-linq-asyncenumerable-singleasync-1(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-boolean))-system-threading-cancellationtoken)
  56. /// <summary>
  57. /// 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.
  58. /// </summary>
  59. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  60. /// <param name="source">Source async-enumerable sequence.</param>
  61. /// <param name="predicate">A predicate function to evaluate for elements in the source sequence.</param>
  62. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  63. /// <returns>ValueTask containing the single element in the async-enumerable sequence that satisfies the condition in the predicate.</returns>
  64. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  65. /// <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>
  66. public static ValueTask<TSource> SingleAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
  67. {
  68. if (source == null)
  69. throw Error.ArgumentNull(nameof(source));
  70. if (predicate == null)
  71. throw Error.ArgumentNull(nameof(predicate));
  72. return Core(source, predicate, cancellationToken);
  73. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  74. {
  75. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  76. {
  77. while (await e.MoveNextAsync())
  78. {
  79. var result = e.Current;
  80. if (predicate(result))
  81. {
  82. while (await e.MoveNextAsync())
  83. {
  84. if (predicate(e.Current))
  85. {
  86. throw Error.MoreThanOneElement();
  87. }
  88. }
  89. return result;
  90. }
  91. }
  92. }
  93. throw Error.NoElements();
  94. }
  95. }
  96. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  97. /// <summary>
  98. /// 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.
  99. /// </summary>
  100. /// <typeparam name="TSource">The type of elements in the source sequence.</typeparam>
  101. /// <param name="source">Source async-enumerable sequence.</param>
  102. /// <param name="predicate">An asynchronous predicate that will be applied to each element of the source sequence.</param>
  103. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  104. /// <returns>ValueTask containing the only element in the async-enumerable sequence that satisfies the condition in the asynchronous predicate.</returns>
  105. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  106. /// <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>
  107. [GenerateAsyncOverload]
  108. [Obsolete("Use SingleAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the SingleAwaitAsync functionality now exists as overloads of SingleAsync.")]
  109. private static ValueTask<TSource> SingleAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  110. {
  111. if (source == null)
  112. throw Error.ArgumentNull(nameof(source));
  113. if (predicate == null)
  114. throw Error.ArgumentNull(nameof(predicate));
  115. return Core(source, predicate, cancellationToken);
  116. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  117. {
  118. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  119. {
  120. while (await e.MoveNextAsync())
  121. {
  122. var result = e.Current;
  123. if (await predicate(result).ConfigureAwait(false))
  124. {
  125. while (await e.MoveNextAsync())
  126. {
  127. if (await predicate(e.Current).ConfigureAwait(false))
  128. {
  129. throw Error.MoreThanOneElement();
  130. }
  131. }
  132. return result;
  133. }
  134. }
  135. }
  136. throw Error.NoElements();
  137. }
  138. }
  139. #if !NO_DEEP_CANCELLATION
  140. [GenerateAsyncOverload]
  141. [Obsolete("Use SingleAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the SingleAwaitWithCancellationAsync functionality now exists as overloads of SingleAsync.")]
  142. private static ValueTask<TSource> SingleAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  143. {
  144. if (source == null)
  145. throw Error.ArgumentNull(nameof(source));
  146. if (predicate == null)
  147. throw Error.ArgumentNull(nameof(predicate));
  148. return Core(source, predicate, cancellationToken);
  149. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  150. {
  151. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  152. {
  153. while (await e.MoveNextAsync())
  154. {
  155. var result = e.Current;
  156. if (await predicate(result, cancellationToken).ConfigureAwait(false))
  157. {
  158. while (await e.MoveNextAsync())
  159. {
  160. if (await predicate(e.Current, cancellationToken).ConfigureAwait(false))
  161. {
  162. throw Error.MoreThanOneElement();
  163. }
  164. }
  165. return result;
  166. }
  167. }
  168. }
  169. throw Error.NoElements();
  170. }
  171. }
  172. #endif
  173. }
  174. }