如何在SelectMany中使用异步lambda?

编程入门 行业动态 更新时间:2024-10-09 19:18:30
本文介绍了如何在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?

本文发布于:2023-11-28 04:44:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   SelectMany   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!