LastOrDefault.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 last 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 last 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?> LastOrDefaultAsync<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 last = await TryGetLast(source, cancellationToken).ConfigureAwait(false);
  27. return last.HasValue ? last.Value : default;
  28. }
  29. }
  30. /// <summary>
  31. /// Returns the last 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 last 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?> LastOrDefaultAsync<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  49. return last.HasValue ? last.Value : default;
  50. }
  51. }
  52. /// <summary>
  53. /// Returns the last element of an async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
  54. /// </summary>
  55. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  56. /// <param name="source">Source async-enumerable sequence.</param>
  57. /// <param name="predicate">An asynchronous predicate function to evaluate for elements in the source sequence.</param>
  58. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  59. /// <returns>ValueTask containing the last element in the async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.</returns>
  60. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  61. [GenerateAsyncOverload]
  62. private static ValueTask<TSource?> LastOrDefaultAwaitAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  72. return last.HasValue ? last.Value : default;
  73. }
  74. }
  75. #if !NO_DEEP_CANCELLATION
  76. [GenerateAsyncOverload]
  77. private static ValueTask<TSource?> LastOrDefaultAwaitWithCancellationAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  87. return last.HasValue ? last.Value : default;
  88. }
  89. }
  90. #endif
  91. private static ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  92. {
  93. if (source is IList<TSource> list)
  94. {
  95. var count = list.Count;
  96. if (count > 0)
  97. {
  98. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[count - 1]));
  99. }
  100. }
  101. else if (source is IAsyncPartition<TSource> p)
  102. {
  103. return p.TryGetLastAsync(cancellationToken);
  104. }
  105. else
  106. {
  107. return Core(source, cancellationToken);
  108. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  109. {
  110. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  111. var hasLast = false;
  112. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  113. {
  114. hasLast = true;
  115. last = item;
  116. }
  117. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  118. }
  119. }
  120. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  121. }
  122. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  123. {
  124. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  125. var hasLast = false;
  126. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  127. {
  128. if (predicate(item))
  129. {
  130. hasLast = true;
  131. last = item;
  132. }
  133. }
  134. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  135. }
  136. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  137. {
  138. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  139. var hasLast = false;
  140. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  141. {
  142. if (await predicate(item).ConfigureAwait(false))
  143. {
  144. hasLast = true;
  145. last = item;
  146. }
  147. }
  148. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  149. }
  150. #if !NO_DEEP_CANCELLATION
  151. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  152. {
  153. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  154. var hasLast = false;
  155. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  156. {
  157. if (await predicate(item, cancellationToken).ConfigureAwait(false))
  158. {
  159. hasLast = true;
  160. last = item;
  161. }
  162. }
  163. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  164. }
  165. #endif
  166. }
  167. }