Suppose I have code that looks like this:
public async Task DoSomethingReturnString(int n) { ... }
int[] numbers = new int[] { 1, 2 , 3};
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));
}