I'm trying to take a Select and project each elements into a Dictionary<string, UdpReceiveResult>
I currently have a Select that just projects the value of a Dictionary to a list tasks of type UdpReceiveResult. clients is a dictionary of type Dictionary<string, UdpClient>. I have
var tasks = clients.Select(c => c.Value.ReceiveAsync()).OrderByCompletion();
I want to project the key and ReceiveAsync() result into a new Dictionary. The OrderByCompletion is from Nito.AsyncEx dll.
2 Answers
Well, for starters, you'll need your result to also include the key:
var tasks = clients.Select(async c => new
{
c.Key,
Value = await c.Value.ReceiveAsync(),
});
Then when the tasks finish you can put them in a dictionary:
var results = await Task.WhenAll(tasks);
var dictionary = results.ToDictionary(
pair => pair.Key, pair => pair.Value);
This code would accomplish the same in one line of code.
var tasks = clients.ToDictionary(c => c.Key, c => c.Value.ReceiveAsync());