There is this answer of a query
I am trying to understand what to put into this LINQ segment
pair => pair.Key, pair => pair.Value
My exact List definition is this:
List<Dictionary<string, StockDetails>> myList = new List<Dictionary<string, StockDetails>>();
This what I attempted but it got flagged for build errors:
IDictionary<string, StockDetails> dictionary = myList.ToDictionary(myList => myList.Key, pair => myList.Value);
As said, I am just trying to understand this LINQ part in how to properly define it for a successful build:
myList => myList.Key, pair => myList.Value);
My build errors are
Error 7 'System.Collections.Generic.Dictionary<string,xx.Models.StockDetails>' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'System.Collections.Generic.Dictionary<string,xx.Models.StockTickerDetails>' could be found (are you missing a using directive or an assembly reference?)
xxxx
Error 9 'System.Collections.Generic.List<System.Collections.Generic.Dictionary<string,xx.Models.StockTickerDetails>>' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'System.Collections.Generic.List<System.Collections.Generic.Dictionary<string,xx.Models.StockDetails>>'
could be found (are you missing a using directive or an assembly reference?)
Thanks for any help
The IDictionary<TKey,TValue> interface is the base interface for generic collections of key/value pairs. Each element is a key/value pair stored in a KeyValuePair<TKey,TValue> object. Each pair must have a unique key. Implementations can vary in whether they allow key to be null .
Dictionary is a collection of keys and values in C#. Dictionary is included in the System. Collection.
One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.
Also you could try something like this:
IDictionary<string, StockDetails> result = myList.SelectMany(d => d).ToDictionary(e=>e.Key,e=>e.Value);
The SelectMany
will project each dictionary as a sequence and it will flatten the resulting sequences into one sequence with all the elements that you have in your dictionaries, so, the result of calling that method is a IEnumerable<KeyValuePair<string, StockDetails>>
. Then you can call the ToDictionary
method like the answer that you quote before with the intention to convert the resulting sequence in a Dictionary<string,StockDetails>
.
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