Working with collections – IAsyncEnumerable

Perhaps the most exciting feature in C# 8.0 was IAsyncEnumerable. At work, we have been dealing with a LOT of async calls. Prior we were having to block the thread just to get the data, and process it accordingly.

One of the more annoying things was converting existing enumerable to IAsyncEnumerable so we wouldn’t have to block the thread and could keep trucking on. The following is a neat little Gist that I partially found and partially developed that I figured I’d show off.

This is an extension method, just drop into your project and call “.SelectAsync” on a collection you want to pull data out of asynchronously as well as convert to an asynchronous enumerable.

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());

Categories: General, Programming

Tags: , ,

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: