Skip to content

Instantly share code, notes, and snippets.

@DCCoder90
Last active September 2, 2023 18:41
Show Gist options
  • Save DCCoder90/d358ace7ef36401dd6f0449d4ab87706 to your computer and use it in GitHub Desktop.
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()
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());
});
}
}
@MelbourneDeveloper
Copy link

MelbourneDeveloper commented May 7, 2021

You can do it like this with System.Linq.Async

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TestProject3
{
    public static class AsyncExtensions
    {
        public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerator<T> enumerator)
        =>
            AsyncEnumerable.Create((cancellationToken)
                => AsyncEnumerator.Create(
                    () => new ValueTask<bool>(enumerator.MoveNext()),
                    () => enumerator.Current,
                    () => new ValueTask())
            );
    }

}

@Magnus12
Copy link

Magnus12 commented May 14, 2021

But in AsyncEnumerable in System.Linq.Async there already is a ToAsyncEnumerable function.
https://github.com/dotnet/reactive/blob/main/Ix.NET/Source/System.Linq.Async/System/Linq/Operators/ToAsyncEnumerable.cs

@MelbourneDeveloper
Copy link

Well, glad to know I was on the right track. If that's the case, why did this gist come up when I Googled for this?

@IanKemp
Copy link

IanKemp commented Jul 21, 2021

Well, glad to know I was on the right track. If that's the case, why did this gist come up when I Googled for this?

AFAIK Google doesn't index GitHub repos directly because source code changes too frequently, but it does index Gists which are relatively static.

@fschwiet
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment