FirstOrDefault.cs 9.4 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. /// <summary>
  12. /// Returns the first element of an async-enumerable sequence, or a default value if no such element exists.
  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>ValueTask containing the first 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. public static ValueTask<TSource?> FirstOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  20. {
  21. if (source == null)
  22. throw Error.ArgumentNull(nameof(source));
  23. return Core(source, cancellationToken);
  24. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  25. {
  26. var first = await TryGetFirst(source, cancellationToken).ConfigureAwait(false);
  27. return first.HasValue ? first.Value : default;
  28. }
  29. }
  30. /// <summary>
  31. /// Returns the first element of an async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
  32. /// </summary>
  33. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  34. /// <param name="source">Source async-enumerable sequence.</param>
  35. /// <param name="predicate">A predicate function to evaluate for elements in the source sequence.</param>
  36. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  37. /// <returns>ValueTask containing the first element in the async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.</returns>
  38. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  39. public static ValueTask<TSource?> FirstOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
  40. {
  41. if (source == null)
  42. throw Error.ArgumentNull(nameof(source));
  43. if (predicate == null)
  44. throw Error.ArgumentNull(nameof(predicate));
  45. return Core(source, predicate, cancellationToken);
  46. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  47. {
  48. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  49. return first.HasValue ? first.Value : default;
  50. }
  51. }
  52. /// <summary>
  53. /// Returns the first element of an async-enumerable sequence that satisfies the condition in the predicate, or a default value if no element satisfies the condition in the predicate.
  54. /// </summary>
  55. /// <typeparam name="TSource">The type of element in the sequence.</typeparam>
  56. /// <param name="source">Source async-enumerable sequence.</param>
  57. /// <param name="predicate">An asynchronous predicate to invoke and await on each element of the sequence.</param>
  58. /// <param name="cancellationToken">An optional cancellation token for cancelling the sequence at any time.</param>
  59. /// <returns>A ValueTask containing the first element in the sequence that satisfies the predicate, or a default value if no element satisfies the predicate.</returns>
  60. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is <see langword="null"/>.</exception>
  61. [GenerateAsyncOverload]
  62. private static ValueTask<TSource?> FirstOrDefaultAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<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, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  70. {
  71. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  72. return first.HasValue ? first.Value : default;
  73. }
  74. }
  75. #if !NO_DEEP_CANCELLATION
  76. [GenerateAsyncOverload]
  77. private static ValueTask<TSource?> FirstOrDefaultAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  78. {
  79. if (source == null)
  80. throw Error.ArgumentNull(nameof(source));
  81. if (predicate == null)
  82. throw Error.ArgumentNull(nameof(predicate));
  83. return Core(source, predicate, cancellationToken);
  84. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  85. {
  86. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  87. return first.HasValue ? first.Value : default;
  88. }
  89. }
  90. #endif
  91. private static ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  92. {
  93. if (source is IList<TSource> list)
  94. {
  95. if (list.Count > 0)
  96. {
  97. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[0]));
  98. }
  99. }
  100. else if (source is IAsyncPartition<TSource> p)
  101. {
  102. return p.TryGetFirstAsync(cancellationToken);
  103. }
  104. else
  105. {
  106. return Core(source, cancellationToken);
  107. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  108. {
  109. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  110. {
  111. if (await e.MoveNextAsync())
  112. {
  113. return new Maybe<TSource>(e.Current);
  114. }
  115. }
  116. return new Maybe<TSource>();
  117. }
  118. }
  119. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  120. }
  121. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  122. {
  123. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  124. {
  125. while (await e.MoveNextAsync())
  126. {
  127. var value = e.Current;
  128. if (predicate(value))
  129. {
  130. return new Maybe<TSource>(value);
  131. }
  132. }
  133. }
  134. return new Maybe<TSource>();
  135. }
  136. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  137. {
  138. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  139. {
  140. while (await e.MoveNextAsync())
  141. {
  142. var value = e.Current;
  143. if (await predicate(value).ConfigureAwait(false))
  144. {
  145. return new Maybe<TSource>(value);
  146. }
  147. }
  148. }
  149. return new Maybe<TSource>();
  150. }
  151. #if !NO_DEEP_CANCELLATION
  152. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  153. {
  154. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  155. {
  156. while (await e.MoveNextAsync())
  157. {
  158. var value = e.Current;
  159. if (await predicate(value, cancellationToken).ConfigureAwait(false))
  160. {
  161. return new Maybe<TSource>(value);
  162. }
  163. }
  164. }
  165. return new Maybe<TSource>();
  166. }
  167. #endif
  168. }
  169. }