对于如何从特定索引处的Dictionary List中获取值感到困惑

时间:2015-03-23 12:55:07

标签: c# winforms

我使用DictionaryList来保存一些来自xml文件的值

这是我的xml文件

<DnsServers>
  <Dns>
    <Name>Google</Name>
    <Value>8.8.8.8,8.8.4.4</Value>
  </Dns>
  <Dns>
    <Name>Telekom</Name>
    <Value>195.175.39.39,195.175.39.40</Value>
  </Dns>
</DnsServers>

然后像这样填充一个组合字符串键值。

void ReadFromDnsServerList()
 {

        _nameValueDictionary = new Dictionary<string, string>();
        //var list = new List<string>();


        XDocument doc = XDocument.Load("DnsServerList.xml");
        if (doc.Root != null)
        {
            var keyValueXml = from c in doc.Root.Descendants("Dns")
                select new
                {
                    name = c.Element("Name").Value,
                    value = c.Element("Value").Value
                };
            foreach (var info in keyValueXml)
            {
                _nameValueDictionary.Add(info.name,info.value);

            }

            foreach (KeyValuePair<string, string> item in _nameValueDictionary)
            {
                cmbDns.Items.Add(item.Key);
            } 

    }

} 

我想知道如何在cmbDns_SelectedIndexChanged中获得相应的dns值 改变这样的事件

name=Google   value =8.8.8.8,8.8.4.4

1 个答案:

答案 0 :(得分:1)

试试这个:

void ReadFromDnsServerList()
{
    _nameValueDictionary = new Dictionary<string, string>();

    XDocument doc = XDocument.Load("DnsServerList.xml");
    if (doc.Root != null)
    {
        var keyValueXml = from c in doc.Root.Descendants("Dns")
            select new
            {
                name = c.Element("Name").Value,
                value = c.Element("Value").Value
            };
        foreach (var info in keyValueXml)
        {
            _nameValueDictionary.Add(info.name, info.value);
        }

        cmbDns.DisplayMember = "Key";
        cmbDns.ValueMember = "Value";
        cmbDns.DataSource = _nameValueDictionary.ToArray();
    }
}

我希望它有所帮助。