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

前端 未结 4 1287
梦毁少年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条回答
  •  执笔经年
    2020-12-10 11:56

    LINQ methods do not support asynchronous actions (e.g., asynchronous value selectors), but you can create one yourself. Here is a reusable ToDictionaryAsync extension method that supports an asynchronous value selector:

    public static class ExtensionMethods
    {
        public static async Task> ToDictionaryAsync(
            this IEnumerable enumerable,
            Func syncKeySelector,
            Func> asyncValueSelector)
        {
            Dictionary dictionary = new Dictionary();
    
            foreach (var item in enumerable)
            {
                var key = syncKeySelector(item);
    
                var value = await asyncValueSelector(item);
    
                dictionary.Add(key,value);
            }
    
            return dictionary;
        }
    }
    

    You can use it like this:

    private static async Task>  DoIt()
    {
        int[] numbers = new int[] { 1, 2, 3 };
    
        return await numbers.ToDictionaryAsync(
            x => x,
            x => DoSomethingReturnString(x));
    }
    

提交回复
热议问题