在C#中向Dictionary添加数据

时间:2010-06-21 06:15:04

标签: c# xml

我有一个像

这样的xml文件
 <Data> 
  <Element ValOne="1" Key="KeyOne" /> 
  <Element ValOne="2" Key="KeyOne" /> 
  <Element ValOne="3" Key="KeyOne" /> 
  <Element ValOne="4" Key="KeyOne" /> 
  <Element ValOne="5" Key="KeyTwo" /> 
  <Element ValOne="6" Key="KeyTwo" /> 
  <Element ValOne="7" Key="KeyThree" /> 
  <Element ValOne="8" Key="KeyThree" /> 
  <Element ValOne="9" Key="KeyThree" /> 
  <Element ValOne="10" Key="KeyThree" /> 
 </Data>

和dictonary

 Dictionary<string, List<string>> m_dictSample = new Dictionary<string, List<string>>();

我需要将文件中的数据添加到dictonary中:

KeyOne       "1"
             "2"
             "3"
             "4"
KeyTwo       "5"
             "6"
KeyThree     "7"
             "8"
             "9"
            "10"

现在我正在使用

List<string> lst = new List<string>();


lst = (XDocument.Load(Application.StartupPath + "\\Sample.xml").Descendants("Element").
            Select(l_Temp => l_Temp.Attribute("Key").Value)).ToList();



 m_dictSample = (from str in lst
                        from el in XDOC.Descendants("Element")
                        where (str == el.Attribute("Key").Value)
                        select new { Key = str, value =new List<string>( el.Attribute("ValOne") }).
                      ToDictionary(l_Temp => l_Temp.Key, l_Temp => l_Temp.value);

但它抛出一个异常,例如“System.Collections.Generic.List.List(int)的最佳重载方法匹配”有一些无效的参数

请给我一个更好的解决方案

提前致谢

2 个答案:

答案 0 :(得分:3)

LINQ通过 lookups

内置了对此的支持
m_dictSample = doc.Descendants("Element")
                  .ToLookup(element => (string) el.Attribute("Key"),
                            element => (string) el.Attribute("ValOne"));

请注意,这将返回ILookup<string, string> - 这不是Dictionary,但它允许您按键查找组,如下所示:

foreach (string value in lookup["some key"])
{
    Console.WriteLine(value);
}

foreach (var group in lookup)
{
    Console.WriteLine(group.Key);
    foreach (string value in group)
    {
        Console.WriteLine("  " + value);
    }
}

如果真的想要Dictionary<string, List<string>>,你可以使用它:

var dictionary = lookup.ToDictionary(group => group.Key,
                                     group => group.ToList());

答案 1 :(得分:3)

如果出于任何原因你想要以经典的方式(我已经建立了它,而Jon发布了它,那么就可以发布它)这里是你如何做到这一点

XDocument document = XDocument.Load(Application.StartupPath + "\\Sample.xml");

Dictionary<string, List<string>> result = (from root in document.Descendants("Element")
                                                       group root by root.Attribute("Key").Value into KeyGroup
                                                       select KeyGroup)
                                                       .ToDictionary(grp => grp.Key, 
                                                                     grp => grp.Attributes("ValOne").Select(at => at.Value).ToList());