Seq toDictionary

How can I build a dictionary from Seq. I can't seem to get the syntax correctly.

So, I have Seq, and I would like to build a dictionary from it, something like

Document

<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) 

but get a runtime error

Error 1 This expression should have been of type XElement, but there is type 'a *' b

+4
source share
2 answers

To build a dictionary from seq, you usually use the dict function. It occupies several key / values ​​of tuples, so the problem boils down to creating this sequence of tuples. With System.Xml.Linq, you move the XML to get the attribute values ​​in the sequence.

Here is the code:

 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 returns the first element of the sequence; it is not useful here if you do not want to use it to go to the Overrides node.

Seq.iter applies the function to each element in a sequence similar to a for / foreach , only for the side-effects of the function. It is not useful here if you do not want to build a dictionary imperatively, i.e. Add key / values ​​to an existing dictionary.

+15
source

In your example, Seq.iter repeats the sequence of XElements tokens. So, for compilation, your lambda should be (fun xel -> xel.Attribute (XName.op_Implicit "key"). Value, xel.Attribute ("value"). Value). However, even if it compiles after this correction, I recommend that you simplify the code using the usinig Mauricio method.

0
source

Source: https://habr.com/ru/post/1401589/


All Articles