【发布时间】:2020-06-19 04:05:46
【问题描述】:
我有 2 个实体:Topic.cs、Lecture.cs、一个模型:TopicModel.cs 和一个异步 repo 调用 repo.GetAllLecturesAsync(string topicId)。这些内容很直观。
我需要异步从 repo 类中获取所有讲座并将它们放入主题模型中。我有以下代码:
List<TopicModel> topicModels = topics.Select(async topic => new TopicModel
{
Lectures = (await repo.GetAllLecturesAsync(topic.Id)).ToList()
}).ToList();
此代码生成以下错误:
"Cannot implicitly convert type 'List<Task<TopicModel>>' to 'List<TopicModel>'"
如何去掉中间的Task?
编辑:
topics 是List<Topic> 的一种。
GetAllLecturesAsync() 返回Task<IEnumerable<Lecture>>。
TopicModel 有一个属性public List<Lecture> Lectures{ get; set; }
【问题讨论】:
-
尝试类似(未经测试)
Lectures = (await repo.GetAllLecturesAsync(topic.Id)).Select(task => task.Result).ToList() -
你的想法是对的,你只需要在第一次选择之后添加 .Select(task => task.Result) 像这样: List
topicModels = topics.Select(async topic => new TopicModel { Lectures = (await repo.GetAllLecturesAsync(topic.Id)).ToList() }).Select(task => task.Result).ToList();修正你的答案,我会接受的。 -
我很困惑为什么你需要额外的
ToList()。ToList()是IEnumerable<T>扩展方法,Select()也是如此。您应该能够在任何您调用ToList()上调用Select()并避免枚举IEnumerable<T>,直到您需要在最后将其转换为列表。 -
哦,我现在明白了,我的困惑是因为您没有指出线路被抛出的位置,我认为它来自属性分配。现在修正我的答案。
-
删除了我的答案。我对 async / await 的理解不足以提供足够的答案。我认为您的代码存在缺陷,我无法识别并认为它只是类型不匹配。试图用你的建议来修正我的答案只会增加混乱。
标签: c# linq async-await