Search code examples
c#async-awaitanonymous-class

WhenAll for anonymous type containing a Task


Is it possible to await a anonymous object (or Tuple, don't care) that contains a Task...better to explain with code...

Lets says we have this:

async Task<Item> GetItem(int i);

Basic case (works):

var itemTasks = new []{1,2,3}.Select(i => GetItem(i)).toArray();
Item[] items = await Task.WhenAll(itemTasks);

what I want to do

var itemTasks = new []{1,2,3}
    .Select(i => new { MyItem = GetItem(i), TheNumber = i })
    .toArray();
//some way to wait for all and get a collection of<anynomous type above> 

Solution

  • You just need to make your lambda async:

    var itemTasks = new []{ 1, 2, 3 }
        .Select(async i => new { MyItem = await GetItem(i), TheNumber = i });
    
    var anonymousObjects = await Task.WhenAll(itemTasks);
    

    The async lambda will implicitly return a Task<AnonymousObject>.


    As an aside, your ToArray() is superfluous, because Task.WhenAll enumerates the Tasks anyway.