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.
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.
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.
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);
Add() Method is used to add a specified key and value to the dictionary. Syntax: public void Add (TKey key, TValue value);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With