Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Hierarchical Parent child

I have a collection of items coming from a database which has a parentid value or null.

Here is my class design:

public class Item
{
public int id{get;set;}
public string Name{get;set;}
public int? ParentId{get;set;}
public List<Item> SubItems{get;set;}
}

I want to build a hierarchical structure of Items from the collection. Assume a collection is 100 items from which I need to construct the structure based on the ParentId mapping.

I tried this post Recursive Hierarchical Joins in C# and LINQ but it gives me an error if ParentId is null.

Also tried Build tree type list by recursively checking parent-child relationship C# , but this solution also does not work for me.

How do I achieve this?

like image 509
Billa Avatar asked Aug 03 '13 06:08

Billa


People also ask

What is parent/child hierarchy?

A parent-child hierarchy is a hierarchy in a dimension that is based on two table columns. Together, these columns define the hierarchical relationships among the members of the dimension. The first column, called the member key column, identifies each dimension member.

How do I create a parent-child hierarchy in SQL Server?

For SQL to do anything with it, a parent-child tree structure has to be stored in a relational database. These structures are usually stored in one table with two ID columns, of which one references a parent object ID. That lets us determine the hierarchy between data.

What is parent/child hierarchy in SSAS?

A parent-child hierarchy is a hierarchy in a standard dimension that contains a parent attribute. A parent attribute describes a self-referencing relationship, or self-join, within a dimension main table. Parent-child hierarchies are constructed from a single parent attribute.

What is a parent-child relationship in a database?

In database management, a relationship between two files. The parent file contains required data about a subject, such as employees and customers. The child is the offspring; for example, an order is the child to the customer, who is the parent.


1 Answers

You could use this approach:

  1. Get all the items from the database (without filling the SubItems).
  2. Build a Lookup<int?,Item> of parent ids and items with that parent id.
  3. Loop through the items and associate each item with the subitems using the lookup.

Code:

var items = // get from the database... (e.g. as a list)
var lookup = items.ToLookup(x => x.ParentId);
foreach (var item in items)
    item.SubItems = lookup[item.Id].ToList();

As @EamonNerbonne commented below, you can get the root elements as well, if you need to:

var roots = lookup[null].ToList();
like image 95
Eren Ersönmez Avatar answered Oct 28 '22 22:10

Eren Ersönmez