Last active
October 2, 2025 14:27
-
-
Save geoder101/70d1daf7cce9f10654712befa7e52cf8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var seq1 = GenerateNumbersAsync("A", 2, 1); | |
| var seq2 = GenerateNumbersAsync("B", 0, 1); | |
| await PrintSeqAsync(seq1); | |
| await PrintSeqAsync(seq2); | |
| async Task PrintSeqAsync( | |
| IAsyncEnumerable<int> seq, | |
| [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(seq))] string label = "") | |
| { | |
| Console.WriteLine($"========== {label} =========="); | |
| await PrintIfAny1Async(seq); | |
| Console.WriteLine("----- vs -----"); | |
| await PrintIfAny2Async(seq); | |
| Console.WriteLine(); | |
| } | |
| async IAsyncEnumerable<int> GenerateNumbersAsync(string label, int count, int delay) | |
| { | |
| Console.WriteLine($"[{label}] START"); | |
| for (var i = 0; i < count; i++) | |
| { | |
| await Task.Delay(delay); | |
| Console.WriteLine($"[{label}] YIELD"); | |
| yield return i; | |
| } | |
| Console.WriteLine($"[{label}] END"); | |
| } | |
| async Task PrintIfAny1Async<T>(IAsyncEnumerable<T> seq) | |
| { | |
| // var (hasAny, items) = (await seq.CountAsync() != 0, seq); // even worse | |
| var (hasAny, items) = (await seq.AnyAsync(), seq); | |
| if (hasAny) | |
| { | |
| await foreach (var item in items) | |
| { | |
| Console.WriteLine(item); | |
| } | |
| } | |
| else | |
| { | |
| Console.WriteLine("No items"); | |
| } | |
| } | |
| async Task PrintIfAny2Async<T>(IAsyncEnumerable<T> seq) | |
| { | |
| var (hasAny, items) = await seq.GetAsyncEnumerableIfAnyAsync(); | |
| if (hasAny) | |
| { | |
| await foreach (var item in items) | |
| { | |
| Console.WriteLine(item); | |
| } | |
| } | |
| else | |
| { | |
| Console.WriteLine("No items"); | |
| } | |
| } | |
| public static class AsyncEnumerableExtensions | |
| { | |
| public static async Task<(bool hasAny, IAsyncEnumerable<T> enumerable)> GetAsyncEnumerableIfAnyAsync<T>( | |
| this IAsyncEnumerable<T> source) | |
| { | |
| var enumerator = source.GetAsyncEnumerator(); | |
| if (!await enumerator.MoveNextAsync()) | |
| { | |
| return (false, AsyncEnumerable.Empty<T>()); | |
| } | |
| return (true, Yield()); | |
| async IAsyncEnumerable<T> Yield() | |
| { | |
| yield return enumerator.Current; | |
| while (await enumerator.MoveNextAsync()) | |
| { | |
| yield return enumerator.Current; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment