Reputation: 523
Well, I recently asked a question on how to populate a Collection with custom data types, but now I can not figure out how to populate a simple string Collection. Maybe somebody is willing to help me out.
My simplified Class Structure:
public class Accommodation
{
[XmlElement("Attribute")]
public Collection<string> Categories;
}
xml looks like:
<Accommodation Id="f7cfc3a5-5b1b-4941-8d7b-f8a4a71fa530">
<Categories>
<Category Id=Time="1abc23"/>
<Category Id=Time="2abc34"/>
</Categories>
</Accommodation>
And that's how my linq statement looks at the moment (I need some help there:
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
Upvotes: 0
Views: 129
Reputation: 523
I now solved it like so, if somebody is curious. But I am sure that my solution involves probably more overhead than necessary.
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();
Upvotes: 0
Reputation: 174289
It looks like you want just this:
doc.Descendants("Accommodation")
.Select(x => new Accomodation { Categories =
x.Element("Categories")
.Elements("Category")
.Select(c => (string)c.Attribute("id")).ToList() });
If Accommodation
is the root tag of the XML it's even simpler:
var accomodation = new Accomodation
{
Categories = doc.Root.Element("Categories")
.Elements("Category")
.Select(c => (string)c.Attribute("id")).ToList()
}
Upvotes: 2