hea*_*ude 3 c# linq idictionary
有一个查询的答案
我试图了解将什么放入这个LINQ细分市场
pair => pair.Key, pair => pair.Value
Run Code Online (Sandbox Code Playgroud)
我的确切列表定义是这样的:
List<Dictionary<string, StockDetails>> myList = new List<Dictionary<string, StockDetails>>();
Run Code Online (Sandbox Code Playgroud)
这是我尝试过但它被标记为构建错误:
IDictionary<string, StockDetails> dictionary = myList.ToDictionary(myList => myList.Key, pair => myList.Value);
Run Code Online (Sandbox Code Playgroud)
如上所述,我只是想了解如何为成功构建正确定义它的LINQ部分:
myList => myList.Key, pair => myList.Value);
Run Code Online (Sandbox Code Playgroud)
我的构建错误是
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?)
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
你也可以试试这样的东西:
IDictionary<string, StockDetails> result = myList.SelectMany(d => d).ToDictionary(e=>e.Key,e=>e.Value);
Run Code Online (Sandbox Code Playgroud)
在SelectMany将项目中的每个字典作为一个序列,它会产生的序列压扁成一个序列与所有你在你的字典具备的要素,因此,调用该方法的结果是一个 IEnumerable<KeyValuePair<string, StockDetails>>.然后你可以ToDictionary 像之前引用的答案一样调用方法,以便在a中转换结果序列Dictionary<string,StockDetails>.