如何在SelectMany中使用异步lambda? [英] How to use async lambda with SelectMany?

查看:273
本文介绍了如何在SelectMany中使用异步lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在IEnumerable.SelectMany中使用async lambda时出现以下错误:

I'm getting the following error when trying to use an async lambda within IEnumerable.SelectMany:

var result = myEnumerable.SelectMany(async (c) => await Functions.GetDataAsync(c.Id));

方法'IEnumerable的类型参数 System.Linq.Enumerable.SelectMany(this IEnumerable,Func>)'不能为 从用法推断.尝试明确指定类型参数

The type arguments for method 'IEnumerable System.Linq.Enumerable.SelectMany(this IEnumerable, Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

其中GetDataAsync定义为:

public interface IFunctions {
    Task<IEnumerable<DataItem>> GetDataAsync(string itemId);
}

public class Functions : IFunctions {
    public async Task<IEnumerable<DataItem>> GetDataAsync(string itemId) {
        // return await httpCall();
    }
}

我猜是因为我的GetDataAsync方法实际上返回了Task<IEnumerable<T>>.但是Select为什么起作用,肯定会引发相同的错误?

I guess because my GetDataAsync method actually returns a Task<IEnumerable<T>>. But why does Select work, surely it should throw the same error?

var result = myEnumerable.Select(async (c) => await Functions.GetDataAsync(c.Id));

有什么办法解决这个问题吗?

Is there any way around this?

推荐答案

异步lambda表达式无法转换为简单的Func<TSource, TResult>.

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

List<DataItem> result = new List<DataItem>();

foreach (var ele in myEnumerable)
{
    result.AddRange(await Functions.GetDataAsyncDo(ele.Id));
}

您不能都不使用yield return-这是设计使然. f.e.:

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
    }

}

这篇关于如何在SelectMany中使用异步lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆