SingleOrDefault.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 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. internal static ValueTask<TSource> SingleOrDefaultAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  92. {
  93. if (source == null)
  94. throw Error.ArgumentNull(nameof(source));
  95. if (predicate == null)
  96. throw Error.ArgumentNull(nameof(predicate));
  97. return Core(source, predicate, cancellationToken);
  98. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  99. {
  100. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  101. {
  102. while (await e.MoveNextAsync())
  103. {
  104. var result = e.Current;
  105. if (await predicate(result).ConfigureAwait(false))
  106. {
  107. while (await e.MoveNextAsync())
  108. {
  109. if (await predicate(e.Current).ConfigureAwait(false))
  110. {
  111. throw Error.MoreThanOneElement();
  112. }
  113. }
  114. return result;
  115. }
  116. }
  117. }
  118. return default!;
  119. }
  120. }
  121. #if !NO_DEEP_CANCELLATION
  122. internal static ValueTask<TSource> SingleOrDefaultAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  123. {
  124. if (source == null)
  125. throw Error.ArgumentNull(nameof(source));
  126. if (predicate == null)
  127. throw Error.ArgumentNull(nameof(predicate));
  128. return Core(source, predicate, cancellationToken);
  129. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  130. {
  131. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  132. {
  133. while (await e.MoveNextAsync())
  134. {
  135. var result = e.Current;
  136. if (await predicate(result, cancellationToken).ConfigureAwait(false))
  137. {
  138. while (await e.MoveNextAsync())
  139. {
  140. if (await predicate(e.Current, cancellationToken).ConfigureAwait(false))
  141. {
  142. throw Error.MoreThanOneElement();
  143. }
  144. }
  145. return result;
  146. }
  147. }
  148. }
  149. return default!;
  150. }
  151. }
  152. #endif
  153. }
  154. }