使用LINQ C#编写xmlelement

时间:2015-11-28 15:35:53

标签: c# linq linq-to-xml

如何使用LINQ将以下内容转换为xml

List<int> calllist = new List<int>();
calllist.Add(10);
calllist.Add(5);
calllist.Add(1);
calllist.Add(20);

输出应为:

<root>
    <child>
        <name>1</name>
        <count>1</count>
    </child>
    <child>
        <name>5</name>
        <count>1</count>
    </child>
    <child>
        <name>10</name>
        <count>1</count>
    </child>
    <child>
        <name>20</name>
        <count>1</count>
    </child>
</root>

我尝试过类似的事情:

XElement root = new XElement ("root", 
    new XElement("child",new XElement(from c in calllist select c; /*error here*/ )));

但是被困了,无法继续。任何人都可以共享解决方案吗?

2 个答案:

答案 0 :(得分:0)

@ user833985

尝试以下内容。

XElement root = new XElement(
            "root", from c in calllist orderby c select
            new XElement("child", 
                 new XElement("name", c),
                  new XElement("count",calllist.Count))

            );

答案 1 :(得分:0)

XElement root = 
  new XElement("root",
    calllist
      .GroupBy(c => c)
      .OrderBy(g => g.Key)
      .Select(g => new XElement("child",
                                new XElement("name", g.Key),
                                new XElement("count",g.Count())
                               )
             )
  );