好吧,我最近问了一个关于如何populate a Collection with custom data types的问题,但现在我无法弄清楚如何填充一个简单的字符串Collection。也许有人愿意帮助我。
我简化的班级结构:
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()))
}
此致
答案 0 :(得分: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()
}
答案 1 :(得分: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();