SingleOrDefault.cs 11 KB

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