LastOrDefault.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 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. internal static ValueTask<TSource> LastOrDefaultAwaitAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  62. return last.HasValue ? last.Value : default!;
  63. }
  64. }
  65. #if !NO_DEEP_CANCELLATION
  66. internal static ValueTask<TSource> LastOrDefaultAwaitWithCancellationAsyncCore<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 last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
  76. return last.HasValue ? last.Value : default!;
  77. }
  78. }
  79. #endif
  80. private static ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  81. {
  82. if (source is IList<TSource> list)
  83. {
  84. var count = list.Count;
  85. if (count > 0)
  86. {
  87. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[count - 1]));
  88. }
  89. }
  90. else if (source is IAsyncPartition<TSource> p)
  91. {
  92. return p.TryGetLastAsync(cancellationToken);
  93. }
  94. else
  95. {
  96. return Core(source, cancellationToken);
  97. static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  98. {
  99. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  100. var hasLast = false;
  101. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  102. {
  103. hasLast = true;
  104. last = item;
  105. }
  106. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  107. }
  108. }
  109. return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
  110. }
  111. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  112. {
  113. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  114. var hasLast = false;
  115. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  116. {
  117. if (predicate(item))
  118. {
  119. hasLast = true;
  120. last = item;
  121. }
  122. }
  123. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  124. }
  125. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  126. {
  127. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  128. var hasLast = false;
  129. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  130. {
  131. if (await predicate(item).ConfigureAwait(false))
  132. {
  133. hasLast = true;
  134. last = item;
  135. }
  136. }
  137. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  138. }
  139. #if !NO_DEEP_CANCELLATION
  140. private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
  141. {
  142. var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
  143. var hasLast = false;
  144. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  145. {
  146. if (await predicate(item, cancellationToken).ConfigureAwait(false))
  147. {
  148. hasLast = true;
  149. last = item;
  150. }
  151. }
  152. return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
  153. }
  154. #endif
  155. }
  156. }