How can I sort a list of entries (Id, ParentId) into a tree hierarchy? [Answered]

I have an unsorted list of entries with two notable fields: Id and ParentId. I would like to sort this data in such a way that if an item has a non-null ParentId, it ends up underneath the parent item with the corresponding Id. The ordering of items at a particular level (e.g. the direct children of a parent) has to be increasing.

The ordering or "root" items (ParentId == null) also has to be increasing. Both Id and ParentId are of type int?. The data hierarchy can be any number of levels deep.

I've tried every LINQ solution from StackOverflow, including a custom one that uses a for loop:
var categories = woo.Category.Enumerate().OrderBy(c => c.id).ToList(); // Source data
var ordered = new ObservableCollection<ProductCategory>(categories);

for (int i = 0; i < ordered.Count; i++)
    var category = ordered[i];
    if (category.parent is null or 0)
        ordered.Move(i, 0); // Move root item to the top, shift everything down
    else if (ordered.FirstOrDefault(o => o.id == category.parent) is { } parent && ordered.IndexOf(parent) is { } parentIndex and > 0)
        ordered.Move(i, parentIndex + 1); // Move item under its parent, shift everything down

but nothing gives the desired result.

I only have to do this once to sort a dataset, so performance and efficiency do not matter at all.
Sounds like you should build the tree, then go through and add to the list based on the location in the tree
I was hoping that there would be a simpler solution, but I will try it. Thanks!
Why not build an actual tree instead of trying to sort it into some flat list?
Building the tree is not too complicated. Then you can build a flat list from it if you really need to. But you can also display it as a hierarchy via TreeView.
Okay, this was the correct solution and it was easier than I was expecting. Thanks for everyone for the help!
UUUnknown User8/26/2022
Message Not Public
Sign In & Join Server To View
✅ This post has been marked as answered!

Looking for more? Join the community!

Recommended Posts
Need Help with creating a JsonSchemaI need to create a JSON-Schema to validate some properties of a json object. I'm using the `oneOf` pError Handling vs Type Enforcement [Answered]In what scenarios would error handling be more effective/efficient and in what scenarios would only Hosting an APIWhat would you guys use to host a websocket stream API such as https://docs.deribit.com/ or https://WPF InputBinding with Mouse4 or Mouse5 (X1 or X2)MouseBinding only seems to support Left, middle and right clicking (and the double click versions) (App.Config vs Resources.resx [Answered]What's the main difference between them also why App.Config considered more secure approach ? 2nd quUsing multiple RateLimiters correctly. [Answered]I'm wrapping an API which requires no more than 4 requests per second **and** 200 per hour, I've gotAbstract List of KeyValuePairs```cs public abstract List<KeyValuePair<string, int>> inventory;``` It says I can't do this with a fDynamic body parameters based on another property in the bodyHi, I'm trying to replicate this api endpoint, but I'm not sure how they made it so you can have difMAUI navigation to new page with injected viewModelIf you think this belong more into #mobile channel I can move, but I think some of you who are morecatching an exception in an async Task [Answered]I can't seem to catch an exception that is thrown in an async Task, I put try/catch within the asyncpass data onclick from one page to another page in asp nethi all, im trying to redirect a page from **Main Page** to **Sub Page** when i click an item on **MASP NET Core default DI-Container, how pass in constructor not-registered parameter? [Answered]I want to create a Model class using a DI container, services registered in the container are passedShould I return the whole created object in POST or just return the id of that object ?When I creating a post method I find myself repeat what I did in GetById Should I just return the Iasp net cshtml javascript filehi all, i have an asp net project (SimpleApp) and in a cshtml file of my **SimpleApp ** project i trChange Visual Studio suggetions with custom analysersHiya.. ohh discords new "forum" channels are super useful for this huh?. anyway. So I managed to impNullReferenceException Object reference not set to an instance of an object```cs List<Effects> effectsList = activePlayerEffects[targetPlayer] ?? new List<Effects>(); ``` some