FirstOrDefault.cs 11 KB

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