1

I'm trying to map ASYNCHRONOUSLY a collection of items, but I retrieve an unexpected type back. Does anyone know how to solve this and explain to me what the problem exactly is? (I'd like to understand why...)

My Code

List<Project> projects = GetProjects();
return projects.Select(async x => await _mapper.Map<Project, ProjectViewModel>(x)).ToArray();

The interface of my mapper is:

public interface IMapper
{
    Task<TDestination> Map<TSource, TDestination>(TSource source);
}

The error

Cannot implicitly convert type 'Task<ProjectViewModel>[]' to 'ProjectViewModel[]'

FYI

I want to have a return type Task<ProjectViewModel[]> for my method

RubenHerman
  • 1,674
  • 6
  • 23
  • 42
  • 2
    That's an async lambda which means it's going to wrap the return value in a Task. I'd suggest you need to make the method that has this code in it async as well and return the appropriate Task type. Note if you need to await all the Tasks you can use `Task.WhenAll` on that array of Tasks. – juharr Aug 09 '18 at 14:14
  • 1
    The `Select` method with `async await` will return results wrapped in `Task` (as though it's a normal synchronous flow). Check this: https://stackoverflow.com/questions/23111031/what-actually-happens-when-using-async-await-inside-a-linq-statement/23113336#23113336 – Fabjan Aug 09 '18 at 14:17
  • Thanks @juharr (and @Fabjan) you set me on the right track. If you'll add your answer, I'll confirm it! – RubenHerman Aug 09 '18 at 14:36

0 Answers0