C# Async Select+ForEach with yield-return

Date: 2020-01-24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AsyncTester
{
    class Program
    {
        public static async Task Main()
        {
            await GetInts()
            .AsyncSelect(x => {
                Console.WriteLine($"Selecting {x}");
                return (x * 2).ToString(); // even convert type
            })
            .AsyncForeach(x => Console.WriteLine(x));


            // C# 8 version, how to select/map data?
            var enumerable = GetIntsAsync();
            await foreach (var i in enumerable)
            {
                Console.WriteLine(i);
            }
        }

        // C# 8 version
        public static async IAsyncEnumerable<int> GetIntsAsync()
        {
            foreach (var item in Enumerable.Range(0, 10)) { 
                await Task.Delay(100);
                yield return item;
            }
        }

        public static IEnumerable<Task<int>> GetInts()
        {
            foreach (var item in Enumerable.Range(0, 10))
                yield return Task.FromResult(item);
        }
    }

    public static class AsyncHelper
    {
        public static async Task AsyncForeach<T>(this IEnumerable<Task<T>> data, Action<T> action)
        {
            foreach (var item in data)
                action(await item.ConfigureAwait(false));
        }
        public static IEnumerable<Task<U>> AsyncSelect<T, U>(this IEnumerable<Task<T>> data, Func<T, U> transform)
        {
            foreach (var item in data)
                yield return Task.Run(async () => transform(await item));
        }
    }
}
32570cookie-checkC# Async Select+ForEach with yield-return