Linq Select into Dictionary

Linq Select into Dictionary

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.

3

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); 
0

This code would accomplish the same in one line of code.

var tasks = clients.ToDictionary(c => c.Key, c => c.Value.ReceiveAsync());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.