尝试用c#从一个有2列(Parent, Category)的数据表创建一个层次结构,可以是N个节点深



我试图用c#创建一个层次结构,从一个数据表2列,(父,类别),可以是N个节点深。

例如

Category Table
=========================
Parent     | Category
=========================
(blank)         root
root            whats-new
whats-new       hair
whats-new       skincare
skincare        face-product

从这个我试图创建如下:

root
root.whats-new
root.whats-new.hair
root.whats-new.skincare
root.whats-new.skincare.face-product

我看了很多例子,但大多数在SQL中显示的例子,但我不确定我应该如何接近它。

我已经能够循环遍历列表并构建3个深度,然而,类别可以是N个节点深度。任何帮助或指导将不胜感激。

我最近做了一些类似的事情,不确定它是否会帮助你,但你可以看到这里的代码:https://github.com/Imdsm/PersonalWebsite/blob/master/PersonalWebsite/Views/Blog/PostArchive.cshtml

这是一个博客存档,所以是year-month-post。

可能最简单的方法,是在父节点的基础上遍历你的列表,比如按类别选择它们没有父节点(好,这是节点1)然后得到所有以当前节点为父节点的类别,好,现在你有了第二级,然后遍历并选择所有以第二个节点为父节点的节点,第三级。

代码方面,我真的帮不上忙,因为我不知道你是如何实现它的。

的例子:

get all cats without parent
get all cats where previous cat is their parent
loop through each of these cats, get all cats where cat(n) is the parent

最后以XML格式解析数据,而不是将其加载到数据表中。它有助于消除大量的开销,同时仍然能够生成所需的层次结构,但代码要少得多。再次感谢您的帮助。

using System.Xml;
// --------------
var doc = new XmlDocument();
doc.Load(@"C:source.xml");
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList=root.SelectNodes("category");
Dictionary<string, string> fullName = new Dictionary<string, string>();
foreach(XmlNode node in nodeList)
{
  string nodeid = node.Attributes["category-id"].Value;
  string parent = node.Attributes["parent"].Value;
  string parentFullname = fullName[parent];
  string nodeFullname = (parentFullname != null) ? parentFullname + "." + nodeid : nodeid;
  fullName[nodeid] = nodeFullname;
}

最新更新