How to hydrate a Dictionary with the results of async calls?

前端 未结 4 1291
梦毁少年i
梦毁少年i 2020-12-10 11:21

Suppose I have code that looks like this:

public async Task DoSomethingReturnString(int n) { ... }
int[] numbers = new int[] { 1, 2 , 3};
         


        
4条回答
  •  萌比男神i
    2020-12-10 11:50

    If you insist on doing it with linq, Task.WhenAll is the key to "hydrate" the dictionary:

    int[] numbers = new int[] { 1, 2 , 3};
    
    KeyValuePair[] keyValArray = //using KeyValuePair<,> to avoid GC pressure
        await Task.WhenAll(numbers.Select(async p => 
            new KeyValuePair(p, await DoSomethingReturnString(p))));
    
    Dictionary dict = keyValArray.ToDictionary(p => p.Key, p => p.Value);
    

提交回复
热议问题