Reputation: 423
I'm trying to create a hierarchy using C# from a datatable with 2 columns, (Parent, Category) that can be N Nodes deep.
For example
Category Table
=========================
Parent | Category
=========================
(blank) root
root whats-new
whats-new hair
whats-new skincare
skincare face-product
From this I am trying to create the following:
root
root.whats-new
root.whats-new.hair
root.whats-new.skincare
root.whats-new.skincare.face-product
I've looked at a lot of examples but most show examples in SQL however I'm not sure how I should approach it.
I've been able to loop through the list and build up to 3 deep however, the categories can be N nodes deep. Any help or direction would be greatly appreciated.
Upvotes: 1
Views: 1047
Reputation: 423
I ended up parsing the data in XML format instead of loading it into a datatable. It helped to remove a lot of the overhead while still giving the ability to generate the needed hierarchy but with a lot less code. Thanks again for your help.
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;
}
Upvotes: 0
Reputation: 7475
I recently did something a bit like this, not sure if it will help you but you can see the code here: https://github.com/Imdsm/PersonalWebsite/blob/master/PersonalWebsite/Views/Blog/PostArchive.cshtml
It was for a blog archive, so year-month-post.
Probably the easiest way, would be to go through your list on a parent by parent basis, such as selecting them all by categories without a parent (ok so that's node one), and then get all categories that have that current node as their parent, ok so now you have the second level, and then go through that and select all the nodes that have each of those second nodes as their parent, third level.
Code wise, I really can't help as I have no idea how you're implementing it.
Example:
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
Upvotes: 1