主要技巧是将字符串放入树结构中。下一个代码片段 (linqpad) 就是这样做的。我不知道输出是否是您可以在客户端处理的东西,但它应该是您可以修改的东西,因为它适合您。
void Main()
{
var rootNode = new Node("root");
foreach(string s in new[] {"Automotive Electronics",
"Automotive Electronics---Body Electronics",
"Automotive Electronics---Body Electronics---Access Control Systems",
"Automotive Electronics---Body Electronics---Body Control Modules",
"Automotive Electronics---Driver Information",
"Automotive Electronics---Driver Information---Clocks",
"Automotive Electronics---Driver Information---Compass Systems",
"Automotive Electronics---HomeL",
"Automotive Electronics---Infotainment & Connectivity",
"Automotive Electronics---Infotainment & Connectivity---Handsfree Systems",
"Automotive Interiors",
"Automotive Interiors---Door Panels",
"Automotive Interiors---Floor Consoles",
"Automotive Interiors---Headliners & Overhead Systems",
"Automotive Interiors---Overhead Consoles",
"Automotive Seating",
"Automotive Seating---Complete Seats",
"Automotive Seating---Complete Seats---SuperThin Seats"})
{
AddNodes(rootNode, s.Split(new[] {"---"}, StringSplitOptions.RemoveEmptyEntries));
}
new JavaScriptSerializer().Serialize(rootNode.Nodes).Dump();
}
public void AddNodes( Node parentNode, string[] names)
{
if (names.Any())
{
var node = parentNode.AddNode(names.First());
AddNodes(node, names.Skip(1).ToArray());
}
}
public class Node
{
public Node(string name)
{
Name = name;
Nodes = new List<Node>();
}
public Node AddNode(string name)
{
if (!this.Nodes.Select(n => n.Name).Contains(name.Trim()))
{
//name.Dump(this.Name);
this.Nodes.Add(new Node(name.Trim()));
}
return this.Nodes.Where (n => n.Name == name).First();
}
public string Name { get;set;}
public List<Node> Nodes { get; set; }
}
输出:
[{"Name":"Automotive Electronics","Nodes":[{"Name":"Body Electronics","Nodes":[{"Name":"Access Control Systems","Nodes":[]}, {"Name":"Body Control Modules","Nodes":[]}]},{"Name":"Driver Information","Nodes":[{"Name":"Clocks","Nodes":[ ]},{"Name":"Compass Systems","Nodes":[]}]},{"Name":"HomeL","Nodes":[]},{"Name":"信息娱乐和连接性" ,"Nodes":[{"Name":"Handsfree Systems","Nodes":[]}]}]},{"Name":"汽车内饰","Nodes":[{"Name":"门面板","节点":[]},{"名称":"落地控制台","节点":[]},{"名称":"顶篷和架空系统","节点":[]},{"名称":"架空控制台","节点":[]}] },{"Name":"Automotive Seating","Nodes":[{"Name":"Complete Seats","Nodes":[{"Name":"SuperThin Seats","Nodes":[]}] }]}]
(请注意,JavaScriptSerializer
您必须在 linqpad 中导入一些命名空间才能运行此代码段)。