如何在c#中向dictonary添加数据

Tho*_*eld 4 c# xml linq winforms

如何从xml文件向dictonary添加数据

之情况:

我宣布像dictonary一样

 Dictonary<string,string> SampleDict=new Dictonary<string,string>();
Run Code Online (Sandbox Code Playgroud)

和我的xml文件是一样的

 <Data>
   <Element ValOne="1" ValTwo="0" />
   <Element ValOne="2" ValTwo="2" />
   <Element ValOne="3" ValTwo="4" />
   <Element ValOne="4" ValTwo="6" />
   <Element ValOne="5" ValTwo="8" />
   <Element ValOne="6" ValTwo="10" />
   <Element ValOne="7" ValTwo="12" />
   <Element ValOne="8" ValTwo="14" />
   <Element ValOne="9" ValTwo="16" />
   <Element ValOne="10" ValTwo="18" />
</Data>
Run Code Online (Sandbox Code Playgroud)

我需要使用LINQ读取"ValOne"和"ValTwo"的值,并将其插入到上面声明的dictonary中

以及如何将dictonary的内容添加到包含两列的列表视图中.

请帮我这样做

提前致谢

Igo*_*aka 6

您可以使用Linq to XML和ToDictionary.

var doc = XDocument.Load("path to xml");
doc.Elements("Element").ToDictionary(
  elem => elem.Attribute("ValOne").Value, //Dictionary key
  elem => elem.Attribute("ValTwo").Value  //Dictionary value
);
Run Code Online (Sandbox Code Playgroud)

这种特殊的重载ToDictionary使用不同的lambda来为生成的集合提取键和值.