45

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
  • 1
    .ToDictionary(x=>x.[key], x=>x.[value]) is a linq function is this not correct, or are you needing an async lambda expression? Commented Sep 17, 2014 at 14:35
  • .ToDictionary(x=>x.[key], x=>x.[value]) only allows you to populate with values from type Task<UdpReceiveResult>. The key is from clients which is a dictionary of type string,UdpClient Commented Sep 17, 2014 at 14:38
  • It does not have to be a select statement. I really just need a way to run the ReceiveAsync()).OrderByCompletion() on each UdpClient and project into a Dictionary<string, UdpReceiveResult>. Commented Sep 17, 2014 at 14:44

2 Answers 2

66

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); 
Sign up to request clarification or add additional context in comments.

Comments

56

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.