(Moderator)
Registriert seit: 25. Jun 2002
Ort: Hausach
7.641 Beiträge
|
AW: Baumstruktur aus Liste erzeugen
13. Jan 2015, 15:51
Also erstmal die Baumstruktur:
Code:
// create test data
var list = new [] {
new Node() { Id=1, Description="Beschreibung 1", ParentId = 0 },
new Node() { Id=2, Description="Beschreibung 2", ParentId = 0 },
new Node() { Id=3, Description="Beschreibung 3", ParentId = 2 },
new Node() { Id=4, Description="Beschreibung 4", ParentId = 2 },
new Node() { Id=5, Description="Beschreibung 5", ParentId = 4 },
new Node() { Id=6, Description="Beschreibung 6", ParentId = 0 },
new Node() { Id=7, Description="Beschreibung 7", ParentId = 6 },
};
// make a lookup to quickly build the structure -> O(n)
var lookup = list.ToLookup(node => node.ParentId);
// hook up the nodes (also O(n))
var tree = new List<Node>();
foreach (var node in list)
{
// if root node, add to tree
if (node.ParentId == 0)
tree.Add(node);
// hook in all children
node.Children = lookup[node.Id].ToList();
}
Was das serialisieren nach Json angeht, schau Dir am besten mal Newtonsoft.Json an: https://www.nuget.org/packages/Newtonsoft.Json/
Das ist *das* Library in .NET wenn es um Json geht. Selbst Microsoft setzt in vielen Teilen seiner Web-Libraries inzwischen darauf.
Das ist dann ein Einzeiler:
Code:
string jsonString = JsonConvert.SerializeObject(tree);
Der JsonString sieht dann so aus:
Code:
[
{"Id":1,"ParentId":0,"Description":"Beschreibung 1","Children":[]},
{"Id":2,"ParentId":0,"Description":"Beschreibung 2","Children":
[
{"Id":3,"ParentId":2,"Description":"Beschreibung 3","Children":[]},
{"Id":4,"ParentId":2,"Description":"Beschreibung 4","Children":
[
{"Id":5,"ParentId":4,"Description":"Beschreibung 5","Children":[]}
]
}
]
},
{"Id":6,"ParentId":0,"Description":"Beschreibung 6","Children":
[
{"Id":7,"ParentId":6,"Description":"Beschreibung 7","Children":[]}
]
}
]
|