简体   繁体   中英

c# xml -> dictionary <string, Tuple<string,string,string>> in Linq

I have this XML Document

<?xml version="1.0" encoding="utf-8"?>
<Tag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <data ID="1" Tag1="A" Tag2="123" Tag3="C" />
  <data ID="2" Tag1="AB" Tag2="12C3" Tag3="D" />
</Tag>

I want the convert the document into Dictionary Type <string, Tuple<string,string,string>>

So basically ID -> Tag1, Tag2, Tag3

I know there are a lot that do Key -> Value like this:

var configDictionary = xdoc.Descendants("data").ToDictionary(
            datum => datum.Attribute("ID").Value,
            datum => datum.Attribute("value").Value);

But i need have the value take in 3 strings.

This is rather simple. All you're missing is a declaration of the tuple using Tuple.Create :

var configDictionary = xdoc.Descendants("data")
             .ToDictionary(
                   datum => datum.Attribute("ID").Value,
                   datum => Tuple.Create(datum.Attribute("Tag1").Value,
                                         datum.Attribute("Tag2").Value,
                                         datum.Attribute("Tag3").Value));

Note this has no validation that the attributes actually exists, which will need to be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM