【问题标题】:How to add data to a dictonary in c#如何在c#中将数据添加到字典中
【发布时间】:2010-05-27 19:53:55
【问题描述】:

如何将数据从 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”的值并将其插入到上述声明的字典中

以及如何将字典的内容添加到包含两列的列表视图中。

请帮我做这件事

提前致谢

【问题讨论】:

  • 论坛HERE好像已经讨论过类似的了
  • 请适当地澄清/重新标记您的问题:您指的是 WPF 中的 ListView 吗? ASP.NET? WinForms?
  • 你为什么使用字典而不是为看似简单的数学运算编写函数?

标签: c# xml winforms linq


【解决方案1】:

您可以为此使用 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 的这种特殊重载使用不同的 lambdas 来为生成的集合提取键和值。

【讨论】:

  • 我认为 MasterGaurav 为将数据绑定到列表视图的问题提供了充分的解决方案。
【解决方案2】:

大概您希望 ValOne 是键,ValTwo 是值?

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

这假设您已将 XML 文件读入 XDocumentXElement

【讨论】:

    【解决方案3】:
    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;
    }
    

    【讨论】:

      【解决方案4】:

      在这种情况下,您可能希望使用数据绑定。看看这篇文章:
      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-20
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        相关资源
        最近更新 更多