Last active
September 2, 2023 18:41
-
-
Save DCCoder90/d358ace7ef36401dd6f0449d4ab87706 to your computer and use it in GitHub Desktop.
Convert IEnumerable to IAsyncEnumerable It has come to my attention that this is at the top of google search results. Before attempting to use this please read the comments below. This is old, and outdated. The comments contain better solutions. TL&DR: use System.Linq.Async's ToAsyncEnumerable()
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
public static class AsyncEnumerableExtensions | |
{ | |
public static IAsyncEnumerable<TResult> SelectAsync<T, TResult>(this IEnumerable<T> enumerable, | |
Func<T, Task<TResult>> selector) | |
{ | |
return AsyncEnumerable.CreateEnumerable(() => | |
{ | |
var enumerator = enumerable.GetEnumerator(); | |
var current = default(TResult); | |
return AsyncEnumerable.CreateEnumerator(async c => | |
{ | |
var moveNext = enumerator.MoveNext(); | |
current = moveNext | |
? await selector(enumerator.Current).ConfigureAwait(false) | |
: default(TResult); | |
return moveNext; | |
}, | |
() => current, | |
() => enumerator.Dispose()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Consider updating the git description with a "TL&DR: use System.Linq.Async's ToAsyncEnumerable()"
Personally I thought it'd be called AsAsyncEnumerable() and turned to Google after that didn't exist.