我正在尝试了解要放入此LINQ段的内容
pair => pair.Key, pair => pair.Value
我的确切列表定义是:
List<Dictionary<string, StockDetails>> myList = new List<Dictionary<string, StockDetails>>();
这是我尝试的但它被标记为构建错误:
IDictionary<string, StockDetails> dictionary = myList.ToDictionary(myList => myList.Key, pair => myList.Value);
如上所述,我只是想了解如何正确定义它以成功构建的LINQ部分:
myList => myList.Key, pair => myList.Value);
我的构建错误是
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?)
感谢您的帮助
答案 0 :(得分:5)
你也可以尝试这样的事情:
IDictionary<string, StockDetails> result = myList.SelectMany(d => d).ToDictionary(e=>e.Key,e=>e.Value);
SelectMany
会将每个字典投影为一个序列,它会将结果序列展平为一个序列,其中包含字典中的所有元素,因此调用该方法的结果为{{1 }}。然后,您可以调用IEnumerable<KeyValuePair<string, StockDetails>>
方法,就像之前quote的答案一样,打算在ToDictionary
中转换结果序列。