我如何从 Seq 构建字典。我似乎无法正确使用语法。
所以我有一个 Seq,我想从中构建一个字典,比如
文档
<Overrides>
<token key="A" value="1"/>
<token key="B" value="2"/>
<token key="C" value="3"/>
<token key="D" value="4"/>
<token key="E" value="5"/>
<token key="F" value="6"/>
let elem = docs |> Seq.map(fun x -> x.Descendants(XName.op_Implicit "Overrides").Elements(XName.op_Implicit "token"))
|> Seq.head
|> Seq.iter(fun (k: XElement , v:XElement) -> k.Attribute(XName.op_Implicit "key").Value, v.Attribute("value").Value)
但得到运行时错误
错误 1 此表达式应具有 XElement 类型,但此处具有类型 'a * 'b
最佳答案
要从 seq 构建字典,您通常使用 dict function .它需要一系列键/值元组,所以问题归结为生成这个元组序列。与 System.Xml.Linq您导航 XML 获取序列中的属性值。
这是代码:
let x = @"<Overrides>
<token key='A' value='1'/>
<token key='B' value='2'/>
<token key='C' value='3'/>
<token key='D' value='4'/>
<token key='E' value='5'/>
<token key='F' value='6'/>
</Overrides>"
#if INTERACTIVE
#r "System.Xml"
#r "System.Xml.Linq"
#endif
open System.Xml.Linq
let docs = XDocument.Parse x
let elem = docs.Root.Descendants(XName.Get "token")
|> Seq.map (fun x -> x.Attribute(XName.Get "key").Value, x.Attribute(XName.Get "value").Value)
|> dict
Seq.head返回序列的第一个元素,除非您想使用它来到达 Overrides 节点,否则在这里没有用。
Seq.iter对序列中的每个元素应用一个函数,很像
for
/foreach
循环,只是为了函数的副作用。除非您想命令式地构建字典,否则它在这里没有用,即将键/值添加到已经存在的字典中。
关于f# - 序列到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719526/