如何将字典列表转换为IDictionary "C#"

8

有一个问题的答案

我试图理解应该在这个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?)

感谢您的帮助。

所以,您有一个字典列表,并希望将该列表转换为单个合并的字典? - poke
我已经删除了我的答案,因为我误读了问题。请包含错误消息(我怀疑是由于在范围内引入myList)并告诉我们您想要实现什么。我以为你有一个键/值对列表,但现在你似乎有一个字典列表... - Jon Skeet
我已经按要求添加了我的错误。非常感谢迄今为止的反馈。 - heavy rocker dude
你说了你尝试过什么,但没有说你想做什么。你想用你的字典列表做什么?你是不是想要一个键值对的列表呢?(就像标题中所述?) - Timothy Shields
我只是在尝试理解如何从myList创建IDictionary。我正在努力弄清楚如何使用LINQ实现这一点。我的意思是,我该如何像Octavio指定的那样定义这些e或d值。到目前为止,没有提到的方法都不起作用。 - heavy rocker dude
听起来你需要一些帮助理解Lambda表达式 - BJ Myers
1个回答

16

还可以尝试类似以下的内容:

IDictionary<string, StockDetails> result = myList.SelectMany(d => d).ToDictionary(e=>e.Key,e=>e.Value);

SelectMany方法将把每个字典投影为一个序列,并将结果序列扁平化为包含所有字典元素的一个序列,因此调用该方法的结果是一个 IEnumerable<KeyValuePair<string, StockDetails>>。之后,您可以像之前回答中 引用 的方式调用ToDictionary方法,以将结果序列转换为Dictionary<string, StockDetails>


抱歉,两个答案都没有提供如何创建IDictionary而不是Dictionary的结果。 - heavy rocker dude
字典基本上是IDictionary。 - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接