JackSojourn
JackSojourn

Reputation: 364

How to call async lamba expression with LINQ Select?

Consider the following code...

List<myobject> items = dbItems.Select(x => ConvertDatabaseItem(x)).ToList();

private async Task<myobject> ConvertDatabaseItem(DataObjects.mydbobject x)
{
    var item = x.ToContract();
    await SetOtherInfo(item);
    return item;
}

This won't compile because we need to await the ConvertDatabaseItem...

List<myobject> items = dbItems.Select(async x => await ConvertDatabaseItem(x)).ToList();

however this will not work because we still need to await the async lamda expression otherwise its a compiler error (List< Task< myobject >> to List< myobject >).

List<myobject> items = dbItems.Select(await (async x => await ConvertDatabaseItem(x))).ToList();

However this gives a 'cannot await lamda expression'.

Am i missing something stupid here or is it not possible to do this?

Upvotes: 4

Views: 723

Answers (2)

JackSojourn
JackSojourn

Reputation: 364

Thanks Didgeridoo...I wound up making the following call...

List<myobject> items = (await Task.WhenAll(dbItems.Select(async x =>
{
    var item = x.ToContract();
    await SetOtherInfo(..., item);
    return item;
}))).ToList();

Upvotes: 0

Didgeridoo
Didgeridoo

Reputation: 1262

Try to use Task.WhenAll method. Your solution will be like this:

var items = await Task.WhenAll(dbItems.Select(ConvertDatabaseItem));

Upvotes: 5

Related Questions