SingleOrDefault.cs 11 KB

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