|
1 |
| -namespace SuperLinq.Async; |
| 1 | +namespace SuperLinq.Async; |
2 | 2 |
|
3 | 3 | public static partial class AsyncSuperEnumerable
|
4 | 4 | {
|
@@ -107,4 +107,43 @@ static async ValueTask<TResult> Core(
|
107 | 107 | : resultSelector(many, default);
|
108 | 108 | }
|
109 | 109 | }
|
| 110 | + |
| 111 | + /// <summary> |
| 112 | + /// Returns the single element in the sequence if it contains exactly one element. |
| 113 | + /// Similar to <see cref="AsyncEnumerable.SingleOrDefaultAsync{TSource}(IAsyncEnumerable{TSource}, CancellationToken)"/>. |
| 114 | + /// </summary> |
| 115 | + /// <typeparam name="TSource"> |
| 116 | + /// The type of the elements of <paramref name="source"/>. |
| 117 | + /// </typeparam> |
| 118 | + /// <param name="source"> |
| 119 | + /// The source sequence. |
| 120 | + /// </param> |
| 121 | + /// <param name="cancellationToken"> |
| 122 | + /// The optional cancellation token to be used for cancelling the sequence at any time. |
| 123 | + /// </param> |
| 124 | + /// <returns> |
| 125 | + /// The single element or the default value of <typeparamref name="TSource"/>. |
| 126 | + /// </returns> |
| 127 | + public static ValueTask<TSource?> TrySingle<TSource>( |
| 128 | + this IAsyncEnumerable<TSource> source, |
| 129 | + CancellationToken cancellationToken = default) |
| 130 | + { |
| 131 | + ArgumentNullException.ThrowIfNull(source); |
| 132 | + |
| 133 | + return Core(source, cancellationToken); |
| 134 | + |
| 135 | + static async ValueTask<TSource?> Core( |
| 136 | + IAsyncEnumerable<TSource> source, |
| 137 | + CancellationToken cancellationToken) |
| 138 | + { |
| 139 | + await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken); |
| 140 | + if (!await e.MoveNextAsync()) |
| 141 | + return default; |
| 142 | + |
| 143 | + var current = e.Current; |
| 144 | + return !await e.MoveNextAsync() |
| 145 | + ? current |
| 146 | + : default; |
| 147 | + } |
| 148 | + } |
110 | 149 | }
|
0 commit comments