原数据
[{
"Id": 1,
"Key": "params",
"Value": "",
"Pid": -1
}, {
"Id": 2,
"Key": "method",
"Value": "Post|Get",
"Pid": 1
}, {
"Id": 3,
"Key": "filter",
"Value": "",
"Pid": 1
}, {
"Id": 4,
"Key": "$and",
"Value": "",
"Pid": 3
}, {
"Id": 5,
"Key": "bo:well",
"Value": "@bo:well",
"Pid": 4
}, {
"Id": 6,
"Key": "it:pt",
"Value": "@it:pt",
"Pid": 4
}]
转换后数据
[{
"Id": 1,
"Key": "params",
"Value": "",
"Pid": -1,
"Children": [{
"Id": 2,
"Key": "method",
"Value": "Post|Get",
"Pid": 1,
"Children": []
}, {
"Id": 3,
"Key": "filter",
"Value": "",
"Pid": 1,
"Children": [{
"Id": 4,
"Key": "$and",
"Value": "",
"Pid": 3,
"Children": [{
"Id": 5,
"Key": "bo:well",
"Value": "@bo:well",
"Pid": 4,
"Children": []
}, {
"Id": 6,
"Key": "it:pt",
"Value": "@it:pt",
"Pid": 4,
"Children": []
}]
}]
}]
}]
实现代码
节点类:
public class Node
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public int Pid { get; set; }
public List<Node> Children { get; set; }
}
public static List<Node> GetTree(List<Node> nodes)
{
List<Node> root = nodes.FindAll(n => n.Pid == -1);
return BuildTree(nodes, root);
}
public static List<Node> BuildTree(List<Node> nodes, List<Node> root)
{
for (int i = 0; i < root.Count; i++)
{
List<Node> children = nodes.FindAll(n => n.Pid == root[i].Id);
BuildTree(nodes, children);
root[i].Children = children;
}
return root;
}