score:18

Accepted answer

async lambda expression cannot be converted to simple func<tsource, tresult>.

so, select many cannot be used. you can run in synchronized context:

myenumerable.select(c => functions.getdataasync(c.id)).selectmany(task => task.result);

or

list<dataitem> result = new list<dataitem>();

foreach (var ele in myenumerable)
{
    result.addrange(await functions.getdataasyncdo(ele.id));
}

you cannot neither use yield return - it is by design. f.e.:

public async task<ienuemrable<dataitem>> do() 
{
    ...
    foreach (var ele in await functions.getdataasyncdo(ele.id)) 
    {
        yield return ele; // compile time error, async method 
                          // cannot be used with yield return
    }

}

score:1

with c#8 and iasyncenumerable we can write this more naturally:

public static async iasyncenumerable<r> 
    selectmanyasync<t, r>(this ienumerable<t> ts, func<t, task<ienumerable<r>>> func)
{
    foreach (var t in ts)
    {
        var rs = await func(t);
        foreach (var r in rs)
            yield return r;
    }
}

note: use async foreach(... to iterate over an iasyncenumerable

score:8

select works because it will return an ienumerable<task<t>>, which can then be awaited with e.g. task.whenall.

so, an easy workaround to this problem is:

ienumerable<task<ienumerable<t>>> tasks = source.select(getnestedenumerabletask);
ienumerable<t>[] nestedresults = await task.whenall(tasks);
ienumerable<t> results = nestedresults.selectmany(nr => nr);

score:58

this is an extension:

public static async task<ienumerable<t1>> selectmanyasync<t, t1>(this ienumerable<t> enumeration, func<t, task<ienumerable<t1>>> func)
{
    return (await task.whenall(enumeration.select(func))).selectmany(s => s);
}

that allows you to run:

var result = await myenumerable.selectmanyasync(c => functions.getdataasync(c.id));

explanation: you have a list of tasks, each returns task<ienumerable<t>>. so you need to fire them all, then await all, and then squash the result via selectmany.


Related Query

More Query from same tag