2017-07-06 90 views
0

对象的名单上有XML描述一些数据是这样的:LINQ查询创建其中每个对象包含一个列表

<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> 

和一些类:

class Person 
{ 
    public string Name { get; set; } 
    public List<Dog> Dogs { get; set; } 
} 

class Dogs 
{ 
    public string Type { get; set; } 
} 

我想使用LINQ XML来查询这些数据,这样我就可以为每个人填充Dog集合来创建一组Person对象。我该怎么做呢?喜欢的东西:

var doc = XDocument.Load("Test.xml"); 
var enumerableOfPeople = from u in doc.Root.Descendants("Person") 
        select new Person() { Name = u.Element("Name").Value, 
              Dogs = /* WHAT GOES HERE */ }; 
+0

你确定你的类是与您的代码正确? – coderwill

+0

我在stackoverflow编辑器中编写了上面的代码,所以可能会有一些小错误,但我认为它给出了一般想法。哪一位不正确让我知道,我会修复它 – user555265

回答

2

这将填充狗:

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() 
         }; 
1
var enumerableOfPeople = doc.Root.Descendants("Person") 
         .Select(u => new Person { 
          Name = u.Element("Name").Value, 
          Dogs = u.Descendants().Select(x => new Dog{ Type = x.Value}).ToList() 
         }); 
1

一个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() 
}); 
+0

OP也使用LINQ。您正在使用LAMBDA语法 –

+0

@RomanoZumbéOh我以为.Select等是linq – EpicKip

+0

两者都是linq的一部分 –

相关问题