首页 > 解决方案 > 从带有等待的 linq 语句中选择

问题描述

这看起来应该很简单,我有以下代码

var additionalInformation=   response.AdditionalInformation.Select( async x =>  new AdditionalInformationItem
                {
                    StatementCode = x?.StatementCode?.Value,
                    LimitDateTime = x?.LimitDateTime?.Item?.Value,
                    StatementTypeCode = x?.StatementTypeCode?.Value,
                    StatementDescription = x?.StatementDescription?.Value,
                    AdditionalInformationResult = await BuildAdditionalInformationPointers(x)


                }).ToList();

我想要实现的是 additionalInformation 的类型

List<AdditionalInformationItem>

,我得到的是List<Task<AdditionalInformationItem>>

谁能帮我正确地重新表述我的陈述?

标签: c#linq.net-coreasync-await

解决方案


您需要使用解包任务,await Task.WhenAll(additionalInformation)然后使用additionalInformation[0].Result.

所以是这样的:

var additionalInformation=   response.AdditionalInformation.Select( async x =>  new AdditionalInformationItem
                {
                    StatementCode = x?.StatementCode?.Value,
                    LimitDateTime = x?.LimitDateTime?.Item?.Value,
                    StatementTypeCode = x?.StatementTypeCode?.Value,
                    StatementDescription = x?.StatementDescription?.Value,
                    AdditionalInformationResult = await BuildAdditionalInformationPointers(x)


                });

await Task.WhenAll(additionalInformation);
//This will iterate the results so may not be the most efficient method if you have a lot of results
List<AdditionalInformationItem> unwrapped = additionalInformation.Select(s => s.Result).ToList();

推荐阅读