So I understand that the await keyword will start a Task, suspend execution, and then later resume execution and return the Task's result at some point in the future after the Task has completed.
In the code below, I am mapping a list of user IDs to a list of email addresses using Select(). The mapping function supplied to Select() will create and await a Task that returns an email address. So execution will be suspended inside the mapping function and then later resumed, where the await keyword will return the email address from the Task, which is then returned by the mapping function.
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
public class Program
{
static void Main()
{
List<int> userIds = new List<int>{54, 24, 67};
List<string> userEmails = userIds.Select
(
async userId => await GetUserEmailAsync(userId)
);
Console.WriteLine("Emails: " + String.Join(", ", userEmails.ToArray()));
}
private static Task<string> GetUserEmailAsync(int userId)
{
return new Task<string>(() => "user" + userId + "@gmail.com");
}
}
However, I get an error describing that the Select() call is returning a list of Tasks instead of strings (the email addresses). But since the mapping function contains the await and returns a string, shouldn't the Select() call return a list of strings?