我正在使用下面的代码循环遍历合同列表并获取每个合同的费率列表。然后将结果存储在字典中。
/// <summary>
/// Get the Rates for the Job keyed to the id of the Organisation
/// </summary>
async Task<Dictionary<int, IReadOnlyList<Rate>>> GetRatesAsync(int jobId)
{
var jobContracts = await _contractClient.GetJobContractsByJobAsync(jobId);
var result = new Dictionary<int, IReadOnlyList<Rate>>();
foreach (var jobContract in jobContracts)
{
result.Add(jobContract.Contract.Organisation.Id, await _contractClient.GetContractRatesByContractAsync(jobContract.Contract.Id));
}
return result;
}
Resharper提醒我,“循环可以转换为LINQ表达式”。然而,Resharper自动生成的修复程序(如下所示)无法编译。
return jobContracts.ToDictionary(jobContract => jobContract.Contract.Organisation.Id, jobContract => await _contractClient.GetContractRatesByContractAsync(jobContract.Contract.Id));
然后
错误是The await operator can only be used within an async lamba expression
。所以加入一个async,并将其更改为以下内容:
return jobContracts.ToDictionary(jobContract => jobContract.Contract.Organisation.Id, async jobContract => await _contractClient.GetContractRatesByContractAsync(jobContract.Contract.Id));
然后
现在出现了错误:无法隐式转换类型 'System.Collections.Generic.Dictionary<int, System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Rate>>>' 为 'System.Collections.Generic.Dictionary<int, System.Collections.Generic.IReadOnlyList<Rate>>'
,它要求我将签名更改为:
async Task<Dictionary<int, Task<IReadOnlyList<Rate>>>> GetContractRatesAsync()
然后
最终更改现在已经编译通过,但是我的所有调用方法都期望等待Dictionary<int, IReadOnlyList<Rate>>
类型的任务,而不是Dictionary<int, Task<IReadOnlyList<Rate>>
。
有没有一种方法可以等待此任务并将其转换为Dictionary<int, IReadOnlyList<Rate>>
?或者其他异步获取数据的方法?