Home > Software engineering >  using Task.WhenAll and Linq Select new object
using Task.WhenAll and Linq Select new object

Time:03-23

I'm trying to figure it there is a way to use Task.WhenAll when constructing anonymous objects in linq. I'm using .net 6.

The vanilla case would look like this, and this works

var taskList = dataSource.Select(d => _client.GetAsync(d.Id));
var taskListResult = await Task.WhenAll(taskList);

I am however trying to construct an object inside the select decorating it with additional properties.

var taskList = dataSource
        .Select(d => new 
        {
            ClientResult = _client.GetAsync(d.Id),
            Id = d.Id,
            OtherProperty = d.Other
        });

var taskListResult = await Task.WhenAll(taskList);

Is there some way to achieve this?

Thanks

CodePudding user response:

Use async-await in the statement lambda which will make it an async one:

var taskList = dataSource
        .Select(async d => new 
        {
            ClientResult = await _client.GetAsync(d.Id),
            Id = d.Id,
            OtherProperty = d.Other
        });

var taskListResult = await Task.WhenAll(taskList);
  • Related