我不想使用foreach
循環兩次,所以我試圖使用LINQ,但不幸的是,這並不工作:轉換詞典<字符串,任務<string>>到詞典<字符串,字符串>
return _etags.ToDictionary(item => item.Key, async item => await item.Value);
誰能告訴我該怎麼做才能改善我的代碼,或者我該如何將Dictionary<string, Task<string>>
轉換爲Dictionary<string, string>
?
這裏是我的代碼:
private static async Task<Dictionary<string, string>> GetETagsAsync(List<string> feedsLink)
{
var eTags = new Dictionary<string, string>(feedsLink.Count);
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
var _eTags = new Dictionary<string, Task<string>>(feedsLink.Count);
eTags = new Dictionary<string, string>(feedsLink.Count);
foreach (string feedLink in feedsLink)
{
if (Uri.IsWellFormedUriString(feedLink, UriKind.Absolute))
{
_eTags.Add(feedLink, GetETagAsync(feedLink));
}
else
{
throw new FormatException();
}
}
foreach (KeyValuePair<string, Task<string>> eTag in _eTags)
{
eTags.Add(eTag.Key, await eTag.Value);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
return eTags;
}
您是否試過'.ToDictionary(item => item.Key,item => item.Value.Result);'? – I4V