我用 c# 编写了以下程序,它正在编译并给我输出,但我没有得到预期的输出
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LINQDemo
{
public class Parent
{
public int ID { get; set; }
public string Name { get; set; }
public List<Child> Childs { get; set; }
public Parent()
{
Childs = new List<Child>();
}
}
public class Child
{
public int ID { get; set; }
public int ParentID { get; set; }
public string ChildName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Parent parent1 = new Parent { ID = 1, Name = "Parent1" };
Parent parent2 = new Parent { ID = 2, Name = "Parent2" };
Child child1= new Child { ID = 1, ParentID = 1, ChildName = "C1" };
Child child2 = new Child { ID = 2, ParentID = 1, ChildName = "C2" };
Child child3 = new Child { ID = 3, ParentID = 2, ChildName = "C3" };
List<Parent> parents = new List<Parent>();
p.Childs.AddRange(new[] { child1, child2 });
p1.Childs.AddRange(new[] { child3 });
ps.Add(parent1);
ps.Add(parent2);
XElement xml = new XElement("Root",
from x in parents
from y in x.Childs where x.ID==y.ParentID
select new XElement("Child",
new XAttribute("ChildID", y.ParentID),
new XElement("ChildName", y.ChildName))
);
Console.WriteLine(xml);
}
}
}
我的输出
<Root>
<Child ChildID="1">
<ChildName>C1</ChildName>
</Child>
<Child ChildID="1">
<ChildName>C2</ChildName>
</Child>
<Child ChildID="2">
<ChildName>C3</ChildName>
</Child>
</Root>
预期产出
<Root>
<Child ChildID="1">
<ChildName>C1</ChildName>
<ChildName>C2</ChildName>
</Child>
<Child ChildID="2">
<ChildName>C3</ChildName>
</Child>
</Root>