C# LINQ查询以创建对象列表,其中每个对象都包含一个列表
我使用XML描述一些数据,如下所示:C# LINQ查询以创建对象列表,其中每个对象都包含一个列表,c#,xml,linq,C#,Xml,Linq,我使用XML描述一些数据,如下所示: <People> <Person> <Name>Alice</Name> <Dogs> <Dog>Labrador</Dog> <Dog>German Shepherd</Dog> </Dogs> </Person>
<People>
<Person>
<Name>Alice</Name>
<Dogs>
<Dog>Labrador</Dog>
<Dog>German Shepherd</Dog>
</Dogs>
</Person>
<Person>
<Name>Bob</Name>
<Dogs>
<Dog>Poodle</Dog>
</Dogs>
</Person>
</People>
这将填充狗:
var enumerableOfPeople = from u in doc.Root.Descendants("Person")
select new Person()
{
Name = u.Element("Name").Value,
Dogs = (from d in u.Element("Dogs").Descendants("Dog")
select new Dog() { Type = d.Value }).ToList()
};
这将填充狗:
var enumerableOfPeople = from u in doc.Root.Descendants("Person")
select new Person()
{
Name = u.Element("Name").Value,
Dogs = (from d in u.Element("Dogs").Descendants("Dog")
select new Dog() { Type = d.Value }).ToList()
};
获得员工的
lambda
方法:
var peeps = doc.Root.Descendants("Person").Select(r => new Person()
{
Name = r.Element("Name").Value,
Dogs = r.Element("Dogs").Descendants("Dog").Select(t => new Dog()
{
Type = t.Value
}).ToList()
});
获得员工的
lambda
方法:
var peeps = doc.Root.Descendants("Person").Select(r => new Person()
{
Name = r.Element("Name").Value,
Dogs = r.Element("Dogs").Descendants("Dog").Select(t => new Dog()
{
Type = t.Value
}).ToList()
});
你确定你的类的代码是正确的吗?我在stackoverflow编辑器中编写了上面的代码,因此可能会有一些小错误,但我认为它给出了总体思路。。哪一位不正确让我知道,我会修正它你确定你的类它与你的代码是正确的吗?我在stackoverflow编辑器中写了上面的代码,所以可能会有一些小错误,但我认为它给出了总体思路。。哪一位不正确请告诉我,我也会修复itOP使用的LINQ。您正在使用LAMBDA syntax,这两个都是linqOP使用的LINQ的一部分。您正在使用LAMBDA syntax,这两者都是linq的一部分
var peeps = doc.Root.Descendants("Person").Select(r => new Person()
{
Name = r.Element("Name").Value,
Dogs = r.Element("Dogs").Descendants("Dog").Select(t => new Dog()
{
Type = t.Value
}).ToList()
});