FirstOrDefault.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. internal static ValueTask<TSource> FirstOrDefaultAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  53. {
  54. if (source == null)
  55. throw Error.ArgumentNull(nameof(source));
  56. if (predicate == null)
  57. throw Error.ArgumentNull(nameof(predicate));
  58. return Core(source, predicate, cancellationToken);
  59. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  60. {
  61. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  62. return first.HasValue ? first.Value : default!;
  63. }
  64. }
  65. #if !NO_DEEP_CANCELLATION
  66. internal static ValueTask<TSource> FirstOrDefaultAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
  67. {
  68. if (source == null)
  69. throw Error.ArgumentNull(nameof(source));
  70. if (predicate == null)
  71. throw Error.ArgumentNull(nameof(predicate));
  72. return Core(source, predicate, cancellationToken);
  73. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  74. {
  75. var first = await TryGetFirst(source, predicate, cancellationToken).ConfigureAwait(false);
  76. return first.HasValue ? first.Value : default!;
  77. }
  78. }
  79. #endif
  80. private static ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  81. {
  82. if (source is IList<TSource> list)
  83. {
  84. if (list.Count > 0)
  85. {
  86. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[0]));
  87. }
  88. }
  89. else if (source is IAsyncPartition<TSource> p)
  90. {
  91. return p.TryGetFirstAsync(cancellationToken);
  92. }
  93. else
  94. {
  95. return Core(source, cancellationToken);
  96. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  97. {
  98. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  99. {
  100. if (await e.MoveNextAsync())
  101. {
  102. return new Maybe<TSource>(e.Current);
  103. }
  104. }
  105. return new Maybe<TSource>();
  106. }
  107. }
  108. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  109. }
  110. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  111. {
  112. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  113. {
  114. while (await e.MoveNextAsync())
  115. {
  116. var value = e.Current;
  117. if (predicate(value))
  118. {
  119. return new Maybe<TSource>(value);
  120. }
  121. }
  122. }
  123. return new Maybe<TSource>();
  124. }
  125. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  126. {
  127. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  128. {
  129. while (await e.MoveNextAsync())
  130. {
  131. var value = e.Current;
  132. if (await predicate(value).ConfigureAwait(false))
  133. {
  134. return new Maybe<TSource>(value);
  135. }
  136. }
  137. }
  138. return new Maybe<TSource>();
  139. }
  140. #if !NO_DEEP_CANCELLATION
  141. private static async ValueTask<Maybe<TSource>> TryGetFirst<TSource>(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 value = e.Current;
  148. if (await predicate(value, cancellationToken).ConfigureAwait(false))
  149. {
  150. return new Maybe<TSource>(value);
  151. }
  152. }
  153. }
  154. return new Maybe<TSource>();
  155. }
  156. #endif
  157. }
  158. }