SuperJMN SuperJMN - 1 month ago 8
C# Question

Mixing LINQ with async (getting payload from a seed)

I have a collection of seeds

var seeds = new [] {1, 2, 3, 4};


From each seed I want to run an async method that performs some calculation with the seed:

async Task<int> Calculation(int seed);


My goal is to perform a select like this:

var results = from seed in seeds
let calculation = await Calculation(seed)
select new { seed, calculation };


Unfortunately, this syntax isn't allowed using LINQ.

How can I make the "results" variable contain both the seed and the calculation?

(I would appreciate any answer, but specially if it's using System.Reactive's
Observable
)

Answer

You could do the following using WhenAll static method:

var result = await Task.WhenAll(seeds.Select(seed => Task.Run(async()=>
                                                 {
                                                   var result=await Calculation(seed);
                                                   return new {Seed=seed,Result=result};
                                                 })));