Carri
Carri

Reputation: 193

Nested hierarchy of objects pattern

I have an object that can have parents and children of the same object type. Is there a standardized way of implementing this pattern?

Something like:

public class Nested
{
   public string Name {get; set;}

   public List<Nested> Parents {get {TODO}}
   public List<Nested> Children {get {TODO}}
}

Upvotes: 4

Views: 2672

Answers (2)

Waleed
Waleed

Reputation: 3145

Take a look on the composite pattern here

Upvotes: 4

carlbenson
carlbenson

Reputation: 3207

From a memory standpoint, it seems like any instance of your class will need to filter through everything recursively to figure out what the relationships are. That's burdensome.

I would recommend just giving your class a property like this (or something more complex, depending on what you're looking to accomplish):

public Nested parent;

This would make it into a linked list. You can separately create a method outside of the class that manages to find parents based on a limited set of parameters (e.g. FindParentsOfNestedToCertainGeneration(int numOfGenerations, Nested child) -- This will just go to child and go up the chain of parents in the "parent" property).

Upvotes: 1

Related Questions