如何在C#中向字典添加数据

4

如何从xml文件向字典中添加数据

场景:

我已经声明了一个字典,像这样:

 Dictonary<string,string> SampleDict=new Dictonary<string,string>();

我的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>

我需要使用LINQ读取"ValOne"和"ValTwo"的值,并将它们插入到上面声明的字典中。如何将字典的内容添加到包含两列的列表视图中?请帮我完成这个操作。谢谢!

似乎已经在论坛上讨论过类似的问题这里 - Incognito
请明确/重新标记您的问题:您是指WPF中的ListView?ASP.NET?还是WinForms? - jeffora
为什么你要使用字典而不是编写一个函数来执行看起来很简单的数学运算? - Instance Hunter
4个回答

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

这个特定的 ToDictionary 重载使用不同的lambda表达式来提取生成集合的键和值。

我认为MasterGaurav对于将数据绑定到ListView的问题提供了一个合适的解决方案。 - Igor Zevaka

4

大概您想让ValOne成为键,ValTwo成为值?

document.Descendants("Element")
    .ToList()
    .ForEach(e => SampleDict[e.Attribute("ValOne").Value] = e.Attribute("ValTwo").Value);

这假设你已经将XML文件读入到一个XDocumentXElement中。

1
XElement allData = XElement.Load("File.xml");
var els = allData.Descendants("Element");

foreach(var xe in els)
{
   SampleDict[xe.Attribute("ValOne").Value] = xe.Attribute("ValTwo").Value;
}

1
你可能想在那种情况下使用数据绑定。看一下这篇文章:
http://www.codeproject.com/KB/miscctrl/DBListViewForV2.aspx

你所需要做的就是...

var items = from xe in els
  select {
    ValOne = xe.Attribute("ValOne").Value,
    ValTwo = xe.Attribute("ValTwo").Value
  }

var arr = items.ToArray();

//private DBListView dataBoundListView;
//dataBoundListView.DataSource = this.bindingSource1;
this.bindingSource1.DataSource = arr;

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