SingleOrDefault.cs 9.5 KB

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