有没有一种简单的方法来循环访问集合并创建报表

本文关键字:访问 循环 集合 合并 报表 创建 方法 简单 一种 有没有 | 更新日期: 2023-09-27 18:33:16

我有以下类型的数据:

class Content {
   public String RowKey ..
   public String Title
}
a collection: ICollection<Content> contentItems

集合的数据如下所示,其中第一列是 RowKey,第二列是标题

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

我要做的是创建以下内容:

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

我可以想办法使用循环、临时变量等来做到这一点,但是有没有办法在 LINQ 中做到这一点?我已经看到了 LINQ 可以做的一些事情,如果您真的知道如何使用它,它似乎可以做很多事情。遗憾的是,我的知识只不过是使用 LINQ 从集合中获取有序数据。

有没有一种简单的方法来循环访问集合并创建报表

以下代码将所需的 html 包装在正文标记中,但您可以轻松地从此元素中提取内容。

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();
}