FirstOrDefault.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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.firstordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-firstordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-threading-cancellationtoken)
  13. /// <summary>
  14. /// Returns the first element of an async-enumerable sequence, or a default value if no such element exists.
  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>ValueTask containing the first 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. public static ValueTask<TSource?> FirstOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  22. {
  23. if (source == null)
  24. throw Error.ArgumentNull(nameof(source));
  25. return Core(source, cancellationToken);
  26. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  27. {
  28. var first = await TryGetFirst(source, cancellationToken).ConfigureAwait(false);
  29. return first.HasValue ? first.Value : default;
  30. }
  31. }
  32. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.firstordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-firstordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-boolean))-system-threading-cancellationtoken)
  33. /// <summary>
  34. /// 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.
  35. /// </summary>
  36. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  37. /// <param name="source">Source async-enumerable sequence.</param>
  38. /// <param name="predicate">A predicate function to evaluate for elements in the source sequence.</param>
  39. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  40. /// <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>
  41. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  42. public static ValueTask<TSource?> FirstOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
  43. {
  44. if (source == null)
  45. throw Error.ArgumentNull(nameof(source));
  46. if (predicate == null)
  47. throw Error.ArgumentNull(nameof(predicate));
  48. return Core(source, predicate, cancellationToken);
  49. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  50. {
  51. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  52. return first.HasValue ? first.Value : default;
  53. }
  54. }
  55. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  56. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.firstordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-firstordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-threading-cancellationtoken-system-threading-tasks-valuetask((system-boolean))))-system-threading-cancellationtoken)
  57. /// <summary>
  58. /// 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.
  59. /// </summary>
  60. /// <typeparam name="TSource">The type of element in the sequence.</typeparam>
  61. /// <param name="source">Source async-enumerable sequence.</param>
  62. /// <param name="predicate">An asynchronous predicate to invoke and await on each element of the sequence.</param>
  63. /// <param name="cancellationToken">An optional cancellation token for cancelling the sequence at any time.</param>
  64. /// <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>
  65. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is <see langword="null"/>.</exception>
  66. [GenerateAsyncOverload]
  67. [Obsolete("Use FirstOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the FirstOrDefaultAwaitAsync functionality now exists as overloads of FirstOrDefaultAsync.")]
  68. private static ValueTask<TSource?> FirstOrDefaultAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<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, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  76. {
  77. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  78. return first.HasValue ? first.Value : default;
  79. }
  80. }
  81. #if !NO_DEEP_CANCELLATION
  82. [GenerateAsyncOverload]
  83. [Obsolete("Use FirstOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the FirstOrDefaultAwaitWithCancellationAsync functionality now exists as overloads of FirstOrDefaultAsync.")]
  84. private static ValueTask<TSource?> FirstOrDefaultAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  85. {
  86. if (source == null)
  87. throw Error.ArgumentNull(nameof(source));
  88. if (predicate == null)
  89. throw Error.ArgumentNull(nameof(predicate));
  90. return Core(source, predicate, cancellationToken);
  91. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  92. {
  93. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  94. return first.HasValue ? first.Value : default;
  95. }
  96. }
  97. #endif
  98. private static ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  99. {
  100. if (source is IList<TSource> list)
  101. {
  102. if (list.Count > 0)
  103. {
  104. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[0]));
  105. }
  106. }
  107. else if (source is IAsyncPartition<TSource> p)
  108. {
  109. return p.TryGetFirstAsync(cancellationToken);
  110. }
  111. else
  112. {
  113. return Core(source, cancellationToken);
  114. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  115. {
  116. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  117. {
  118. if (await e.MoveNextAsync())
  119. {
  120. return new Maybe<TSource>(e.Current);
  121. }
  122. }
  123. return new Maybe<TSource>();
  124. }
  125. }
  126. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  127. }
  128. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  129. {
  130. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  131. {
  132. while (await e.MoveNextAsync())
  133. {
  134. var value = e.Current;
  135. if (predicate(value))
  136. {
  137. return new Maybe<TSource>(value);
  138. }
  139. }
  140. }
  141. return new Maybe<TSource>();
  142. }
  143. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  144. {
  145. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  146. {
  147. while (await e.MoveNextAsync())
  148. {
  149. var value = e.Current;
  150. if (await predicate(value).ConfigureAwait(false))
  151. {
  152. return new Maybe<TSource>(value);
  153. }
  154. }
  155. }
  156. return new Maybe<TSource>();
  157. }
  158. #if !NO_DEEP_CANCELLATION
  159. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  160. {
  161. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  162. {
  163. while (await e.MoveNextAsync())
  164. {
  165. var value = e.Current;
  166. if (await predicate(value, cancellationToken).ConfigureAwait(false))
  167. {
  168. return new Maybe<TSource>(value);
  169. }
  170. }
  171. }
  172. return new Maybe<TSource>();
  173. }
  174. #endif
  175. }
  176. }