LINQ methods do not support asynchronous actions (for example, asynchronous value selectors), but you can create them yourself. Here is a reusable ToDictionaryAsync extension method that supports an asynchronous value selector:
public static class ExtensionMethods { public static async Task<Dictionary<TKey, TValue>> ToDictionaryAsync<TInput, TKey, TValue>( this IEnumerable<TInput> enumerable, Func<TInput, TKey> syncKeySelector, Func<TInput, Task<TValue>> asyncValueSelector) { Dictionary<TKey,TValue> dictionary = new Dictionary<TKey, TValue>(); foreach (var item in enumerable) { var key = syncKeySelector(item); var value = await asyncValueSelector(item); dictionary.Add(key,value); } return dictionary; } }
You can use it as follows:
private static async Task<Dictionary<int,string>> DoIt() { int[] numbers = new int[] { 1, 2, 3 }; return await numbers.ToDictionaryAsync( x => x, x => DoSomethingReturnString(x)); }
Yacoub massad
source share