2013-03-06 65 views
0

那麼,我最近問了一個關於如何populate a Collection with custom data types的問題,但現在我無法弄清楚如何填充一個簡單的字符串Collection。也許有人願意幫助我。Linq xml to object - 如何填充集合<string>

我簡單的階層結構:

public class Accommodation 
{ 
    [XmlElement("Attribute")] 
    public Collection<string> Categories;   
} 

XML是什麼樣子:

<Accommodation Id="f7cfc3a5-5b1b-4941-8d7b-f8a4a71fa530"> 
    <Categories> 
    <Category Id=Time="1abc23"/> 
    <Category Id=Time="2abc34"/> 
    </Categories> 
</Accommodation> 

這就是我的LINQ語句怎麼看的那一刻(我需要一些幫助有:

from x in doc.Descendants("Accommodation") 
select new Accommodation() 
{ 
    Categories = new Collection<string>(x.Descendants("Categories").SelectMany(
    categories => categories.Elements("Category").Select(
    (string)x.Element("Categories").Element("Category").Attributes("Id")).ToList())) 
} 

Regards

回答

0

我現在解決它像這樣,如果有人好奇。但我相信我的解決方案可能涉及更多的開銷。

IEnumerable<Accommodation> temp = 
    (from x in doc.Descendants("Accommodation") 
     select new Accommodation() 
     { 
      Categories = new Collection<string>(
       x.Descendants("Categories").SelectMany(categories 
        => categories.Elements("Category").Select(category 
         => category.Attribute("Id").Value ?? "")).ToList()) 
     }).ToList(); 
2

它看起來像你只想要這個:

doc.Descendants("Accommodation") 
    .Select(x => new Accomodation { Categories = 
        x.Element("Categories") 
        .Elements("Category") 
        .Select(c => (string)c.Attribute("id")).ToList() }); 

如果Accommodation是XML的根標籤這是更簡單:

var accomodation = new Accomodation 
{ 
    Categories = doc.Root.Element("Categories") 
         .Elements("Category") 
         .Select(c => (string)c.Attribute("id")).ToList() 
}