Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 272
JackSojourn Avatar asked Oct 25 '25 16:10

JackSojourn


1 Answers

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

var items = await Task.WhenAll(dbItems.Select(ConvertDatabaseItem));
like image 128
Didgeridoo Avatar answered Oct 27 '25 06:10

Didgeridoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!