LastOrDefault.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-threading-cancellationtoken)
  13. /// <summary>
  14. /// Returns the last 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 last 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?> LastOrDefaultAsync<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 last = await TryGetLast(source, cancellationToken).ConfigureAwait(false);
  29. return last.HasValue ? last.Value : default;
  30. }
  31. }
  32. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-boolean))-system-threading-cancellationtoken)
  33. /// <summary>
  34. /// 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.
  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 last 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?> LastOrDefaultAsync<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  52. return last.HasValue ? last.Value : default;
  53. }
  54. }
  55. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  56. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-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 last element of an async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
  59. /// </summary>
  60. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  61. /// <param name="source">Source async-enumerable sequence.</param>
  62. /// <param name="predicate">An asynchronous predicate function to evaluate for elements in the source sequence.</param>
  63. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  64. /// <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>
  65. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  66. [GenerateAsyncOverload]
  67. [Obsolete("Use LastOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the LastOrDefaultAwaitAsync functionality now exists as overloads of LastOrDefaultAsync.")]
  68. private static ValueTask<TSource?> LastOrDefaultAwaitAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  78. return last.HasValue ? last.Value : default;
  79. }
  80. }
  81. #if !NO_DEEP_CANCELLATION
  82. [GenerateAsyncOverload]
  83. [Obsolete("Use LastOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the LastOrDefaultAwaitWithCancellationAsync functionality now exists as overloads of LastOrDefaultAsync.")]
  84. private static ValueTask<TSource?> LastOrDefaultAwaitWithCancellationAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  94. return last.HasValue ? last.Value : default;
  95. }
  96. }
  97. #endif
  98. private static ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  99. {
  100. if (source is IList<TSource> list)
  101. {
  102. var count = list.Count;
  103. if (count > 0)
  104. {
  105. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[count - 1]));
  106. }
  107. }
  108. else if (source is IAsyncPartition<TSource> p)
  109. {
  110. return p.TryGetLastAsync(cancellationToken);
  111. }
  112. else
  113. {
  114. return Core(source, cancellationToken);
  115. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  116. {
  117. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  118. var hasLast = false;
  119. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  120. {
  121. hasLast = true;
  122. last = item;
  123. }
  124. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  125. }
  126. }
  127. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  128. }
  129. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  130. {
  131. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  132. var hasLast = false;
  133. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  134. {
  135. if (predicate(item))
  136. {
  137. hasLast = true;
  138. last = item;
  139. }
  140. }
  141. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  142. }
  143. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  144. {
  145. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  146. var hasLast = false;
  147. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  148. {
  149. if (await predicate(item).ConfigureAwait(false))
  150. {
  151. hasLast = true;
  152. last = item;
  153. }
  154. }
  155. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  156. }
  157. #if !NO_DEEP_CANCELLATION
  158. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  159. {
  160. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  161. var hasLast = false;
  162. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  163. {
  164. if (await predicate(item, cancellationToken).ConfigureAwait(false))
  165. {
  166. hasLast = true;
  167. last = item;
  168. }
  169. }
  170. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  171. }
  172. #endif
  173. }
  174. }