Reputation:
I have the following kind of data:
class Content {
public String RowKey ..
public String Title
}
a collection: ICollection<Content> contentItems
Data for the collection looks like this where the first column is the RowKey and the second the Title
1.0 Topic1
1.1 Some text for topic1
1.2 More text for topic1
2.0 Topic2 header
2.1 Some text for topic2
2.3 Some more text for topic2
What I to do is to create the following:
<h2>1 Topic1</h2>
<ul>
<li>1.1 Some text for topic1</li>
<li>1.2 More text for topic1</li>
</ul>
<h2>2 Topic2 header</h2>
<ul>
<li>2.1 Some text for topic2</li>
<li>2.3 Some more text for topic2</li>
</ul>
I can think of ways to do this using loops, temp variables and the like but is there a way I can do this in LINQ? I have seen some things the LINQ can do and it seems like it can do very much if you really know how to use it. Unfortunately my knowledge is little more than getting ordered data out of a collection using LINQ.
Upvotes: 1
Views: 89
Reputation: 848
The following code wraps the required html in a body tag but you can easily extract the content from this element.
private static void BuildHtml()
{
var content = new List<Content>
{
new Content() { RowKey= "1.0", Title = "Topic1" },
new Content() { RowKey= "1.1", Title = "Some text for topic1" },
new Content() { RowKey= "1.2", Title = "More text for topic1" },
new Content() { RowKey= "2.0", Title = "Topic2 header" },
new Content() { RowKey= "2.1", Title = "Some text for topic2" },
new Content() { RowKey= "2.3", Title = "Some more text for topic2" }
};
var html = new XElement("Body", content
.GroupBy(x => x.RowKey.Split('.').First())
.Select(
y =>
new List<XElement>
{
new XElement("h2", y.First().RowKey.Split('.').First() + " " + y.First().Title,
new XElement("ul", y.Skip(1).Select(z => new XElement("li", z.RowKey + " " + z.Title))))
}));
html.ToString();
}
Upvotes: 1