gpt4 book ai didi

C# 使用递归从 List 创建 HTML 无序列表

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:56 26 4
gpt4 key购买 nike

是否可以使用递归输出如下HTML无序列表。

<ul>
<li>1
<ul>
<li>5
<ul>
<li>8</li>
<li>9</li>
</ul>
</li>
<li>6</li>
</ul>
</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>7</li>
</ul>

原始数据所在的位置在下面的列表中

        List<Page> pages = new List<Page>();

pages.Add(new Page { Id = 1, pageId = 1, parentPageId = 0 });
pages.Add(new Page { Id = 2, pageId = 2, parentPageId = 0 });
pages.Add(new Page { Id = 3, pageId = 3, parentPageId = 0 });
pages.Add(new Page { Id = 4, pageId = 4, parentPageId = 0 });
pages.Add(new Page { Id = 5, pageId = 5, parentPageId = 1 });
pages.Add(new Page { Id = 6, pageId = 6, parentPageId = 1 });
pages.Add(new Page { Id = 7, pageId = 7, parentPageId = 0 });
pages.Add(new Page { Id = 8, pageId = 8, parentPageId = 5 });
pages.Add(new Page { Id = 9, pageId = 9, parentPageId = 5 });

页面在哪里

    public class Page
{
public int Id { get; set; }
public int pageId { get; set; }
public int parentPageId { get; set; }
}

这是我到目前为止所拥有的,当然还不能完全奏效......

        foreach (var page in pages)
{
Console.WriteLine("<ul><li>{0}", page.pageId);
WriteMenu(pages, page.pageId, page.parentPageId);
}


public static void WriteMenu(List<Page> pages, int pageId, int parentPageId)
{
foreach (var page in pages)
{
if (page.parentPageId == pageId)
{
Console.WriteLine("<ul><li>{0}", page.pageId);
WriteMenu(pages, page.pageId, page.parentPageId);
}
}
}

最佳答案

怎么样:

public static bool WriteMenu(List<Page> pages, int parentId, int indent)
{
string padding = new string(' ', indent * 8);
bool writtenAny = false;
foreach (var page in pages.Where(p => p.ParentPageId == parentId))
{
if (!writtenAny)
{
Console.WriteLine();
Console.WriteLine(padding + "<ul>");
writtenAny = true;
}
Console.Write(padding + " <li>{0}", page.PageId);
if (WriteMenu(pages, page.PageId, indent + 1))
{
Console.WriteLine(padding + " </li>");
}
else
{
Console.WriteLine("</li>");
}
}
if (writtenAny)
{
Console.WriteLine(padding + "</ul>");
}
return writtenAny;
}
...
WriteMenu(pages, 0, 0);

关于C# 使用递归从 List 创建 HTML 无序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3416899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com