转换列表<Task<T>>> 到列表<T>

问题描述 投票:0回答:1

我有这个变量应该投影并返回

AttachmentRequestModel
列表,如下所示:

 var mappedAttachments = recordAction
     .PPAttachments
     .Select(async x => new AttachmentRequestModel()
     {
         AttachmentId = 1,
         AttachmentContent = await GetReportAttachContentAsync(1),
         AttachmentName = "name",
         AttachmentType = 1
     })
     .ToList();

mappedAttachments
变量返回
List<Task<AttachmentRequestModel>>
我怎样才能将其更改为返回
List<AttachmentRequestModel>

编辑:我更改了代码,循环遍历列表中的每个任务并等待它,如下所示:

var anotherAttachList = new List<AttachmentRequestModel>();
foreach (var attachTask in mappedAttachments)
    anotherAttachList.Add(await attachTask);

我想知道是否有更好的方法来做到这一点。

c# linq collections
1个回答
0
投票

尝试使用

Task.WhenAll
+
SelectMay()
,

的组合
 var mappedAttachments = (await Task.WhenAll(recordAction.PPAttachments
     .SelectMany(async x => new AttachmentRequestModel()
     {
         AttachmentId = 1,
         AttachmentContent = await GetReportAttachContentAsync(1),
         AttachmentName = "name",
         AttachmentType = 1
     })))
     .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.