Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Select into Dictionary

Tags:

c#

linq

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.

like image 426
Jesse Avatar asked Sep 17 '14 14:09

Jesse


People also ask

How to convert LINQ result to Dictionary?

In LINQ, ToDictionary() Method is used to convert the items of list/collection(IEnumerable<T>) to new dictionary object (Dictionary<TKey,TValue>) and it will optimize the list/collection items by required values only.

How do you retrieve a value for a key in a Dictionary C#?

The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.

What is ToDictionary?

The ToDictionary method is an extension method in C# and converts a collection into Dictionary. Firstly, create a string array − string[] str = new string[] {"Car", "Bus", "Bicycle"}; Now, use the Dictionary method to convert a collection to Dictionary − str.ToDictionary(item => item, item => true);

How do you add to a Dictionary in C#?

Add() Method is used to add a specified key and value to the dictionary. Syntax: public void Add (TKey key, TValue value);


1 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);  
like image 138
Servy Avatar answered Sep 24 '22 03:09

Servy