Single.cs 10 KB

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