这看起来应该很简单,我有以下代码
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>>
有人可以帮助我正确地重新陈述我的陈述吗?
答案 0 :(得分:5)
您需要使用Array
(
[0] => Array
(
[0] => Duits adres en services
[1] => project:096b2fc2bc5133784c13c77ab857ae53
[2] =>
)
[1] => Array
(
[0] => Duits adres en services
[1] => project:5e920f34c4712abc4c13c77ab857ae53
[2] =>
)
[2] => Array
(
[0] => Campagne management
[1] => project:52e5cc976d1b98db4c13c77ab857ae53
[2] =>
)
[3] => Array
(
[0] => Duits adres en services
[1] => project:52e5cc976d1b98db4c13c77ab857ae53
[2] =>
)
[4] => Array
(
[0] => Duits adres en services
[1] => project:d4b09419caff744f4c13c77ab857ae53
[2] =>
)
)
解开任务,然后使用await Task.WhenAll(additionalInformation)
访问实际结果。
是这样的:
additionalInformation[0].Result
答案 1 :(得分:1)
await Task.WhenAll
将自动解包任务,并将结果交给您。
AdditionalInformationItem[] additionalInformation = await Task.WhenAll(
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)
});
);
答案 2 :(得分:0)
实际上没有办法在简单的lambda表达式中执行此操作。异步Lambda表达式将始终返回Task<T>
。因此,您可以快速而肮脏地在.Result
上调用Task
(不要这样做!除非您像Liam的answer中那样先等待),否则只需初始化一个新列表并在foreach循环中添加项目:
var additionalInformation = new List<AdditionalInformationItem>();
foreach (var x in response.AdditionalInformation)
{
var item = new AdditionalInformationItem
{
StatementCode = x?.StatementCode?.Value,
LimitDateTime = x?.LimitDateTime?.Item?.Value,
StatementTypeCode = x?.StatementTypeCode?.Value,
StatementDescription = x?.StatementDescription?.Value,
AdditionalInformationResult = await BuildAdditionalInformationPointers(x)
};
additionalInformation.Add(item);
}