LastOrDefault.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-threading-cancellationtoken)
  17. /// <summary>
  18. /// Returns the last 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 last 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?> LastOrDefaultAsync<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 last = await TryGetLast(source, cancellationToken).ConfigureAwait(false);
  33. return last.HasValue ? last.Value : default;
  34. }
  35. }
  36. // 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)
  37. /// <summary>
  38. /// 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.
  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 last 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?> LastOrDefaultAsync<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  56. return last.HasValue ? last.Value : default;
  57. }
  58. }
  59. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  60. // 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)
  61. /// <summary>
  62. /// 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.
  63. /// </summary>
  64. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  65. /// <param name="source">Source async-enumerable sequence.</param>
  66. /// <param name="predicate">An asynchronous predicate function to evaluate for elements in the source sequence.</param>
  67. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  68. /// <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>
  69. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
  70. [GenerateAsyncOverload]
  71. [Obsolete("Use LastOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the LastOrDefaultAwaitAsync functionality now exists as overloads of LastOrDefaultAsync.")]
  72. private static ValueTask<TSource?> LastOrDefaultAwaitAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  82. return last.HasValue ? last.Value : default;
  83. }
  84. }
  85. #if !NO_DEEP_CANCELLATION
  86. [GenerateAsyncOverload]
  87. [Obsolete("Use LastOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the LastOrDefaultAwaitWithCancellationAsync functionality now exists as overloads of LastOrDefaultAsync.")]
  88. private static ValueTask<TSource?> LastOrDefaultAwaitWithCancellationAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  98. return last.HasValue ? last.Value : default;
  99. }
  100. }
  101. #endif
  102. private static ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  103. {
  104. if (source is IList<TSource> list)
  105. {
  106. var count = list.Count;
  107. if (count > 0)
  108. {
  109. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[count - 1]));
  110. }
  111. }
  112. else if (source is IAsyncPartition<TSource> p)
  113. {
  114. return p.TryGetLastAsync(cancellationToken);
  115. }
  116. else
  117. {
  118. return Core(source, cancellationToken);
  119. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  120. {
  121. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  122. var hasLast = false;
  123. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  124. {
  125. hasLast = true;
  126. last = item;
  127. }
  128. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  129. }
  130. }
  131. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  132. }
  133. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  134. {
  135. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  136. var hasLast = false;
  137. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  138. {
  139. if (predicate(item))
  140. {
  141. hasLast = true;
  142. last = item;
  143. }
  144. }
  145. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  146. }
  147. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  148. {
  149. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  150. var hasLast = false;
  151. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  152. {
  153. if (await predicate(item).ConfigureAwait(false))
  154. {
  155. hasLast = true;
  156. last = item;
  157. }
  158. }
  159. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  160. }
  161. #if !NO_DEEP_CANCELLATION
  162. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  163. {
  164. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  165. var hasLast = false;
  166. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  167. {
  168. if (await predicate(item, cancellationToken).ConfigureAwait(false))
  169. {
  170. hasLast = true;
  171. last = item;
  172. }
  173. }
  174. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  175. }
  176. #endif
  177. }
  178. }