❔ Sorting a list of objects into a tree structure

I have a set of objects that looks roughly like this: class Item { public uint Id; public uint ParentId; } To visualize the data I want to sort the data into a graph. Is there a built in way of doing this in C#? For the actual visualisation I am happy with just viewing it in the debugger. The reason for asking the question instead of just doing it is that I want to get better at using built in functionality. I string.Join(", ", array) was a game changer for example
5 Replies
Denis
Denis2y ago
You wish to visualize what exactly? And what kind of graph are you talking about? In the VS Debugger you are able to view, e.g., contents of a collection. Is this what you want?
Ole (ping please)
The actual visualization is not important, I was mostly interested in finding out if there was a somewhat built in way in c# to turn a flat structure into a tree. I do this a fair bit for different data structures and it would be nice to learn a 'trick' if there is one. I threw this together:
var rootItems = new List<TreeBusItem>();
var roots = busses.Where(x => x.OverrideBusId == 0).ToList();
roots.ForEach(x => rootItems.Add(new TreeBusItem(x, audioRepo)));

foreach (var item in roots)
busses.Remove(item);

while (busses.Count != 0)
{
var toDelete = new List<CAkBus_v136>();
foreach(var bus in busses)
{
var parent = FindParent(rootItems, bus.OverrideBusId);
if(parent != null)
toDelete.Add(bus);

parent.Children.Add(new TreeBusItem(bus, audioRepo));
}

foreach (var item in toDelete)
busses.Remove(item);
}
var rootItems = new List<TreeBusItem>();
var roots = busses.Where(x => x.OverrideBusId == 0).ToList();
roots.ForEach(x => rootItems.Add(new TreeBusItem(x, audioRepo)));

foreach (var item in roots)
busses.Remove(item);

while (busses.Count != 0)
{
var toDelete = new List<CAkBus_v136>();
foreach(var bus in busses)
{
var parent = FindParent(rootItems, bus.OverrideBusId);
if(parent != null)
toDelete.Add(bus);

parent.Children.Add(new TreeBusItem(bus, audioRepo));
}

foreach (var item in toDelete)
busses.Remove(item);
}
I am not really interested in feedback on this as the code will just be thrown out again, but if there is a clever linq way to do something like this let me know 🙂 With the temp data class TreeBusItem and the FindParent its about 100 lines which is a lot of wasted time for something like this.
Denis
Denis2y ago
Afaik, LINQ does not provide any direct and quick way to create tree structures You'd have to write your own algorithm for constructing such data
Ole (ping please)
I feared so
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server