Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all subobjects from a CustomObject with n Children/Subchildren and so on

I have a CustomObject with n Children. These children are a List of CustomObjects. Something like this:

public class CustomObject
{
    public List<CustomObject> Children = new List<CustomObject>();
}

What I am looking for is the most performant way to get ALL n Children and their children and subchildren etc, from a single instance of CustomObject. Is there a better way than looping through all veigns until I reach the end (null)?

(C#, .NET 3.5)

To make it more clear, I will make an example structure:

//root object
CustomObject.Children ->
    CustomObject.Children ->
         CustomObject
         CustomObject
    CustomObject.Children ->
         CustomObject.Children ->
             CustomObject
         CustomObject
    CustomObject

In this case, I need to get ALL custom objects beneath the root object.

like image 679
LMW-HH Avatar asked Dec 05 '22 18:12

LMW-HH


1 Answers

No, you just have to loop through everything. You can use a recursive method:

public void GetItems(List<CustomObject> list) {
  list.Add(this);
  foreach (CustomObject child in Childs) {
    child.GetItems(list);
  }
}

Usage:

List<CustomObject> items = new List<CustomObject>();
someCustomObject.GetItems(items);

Note: The plural form of child is children.

like image 120
Guffa Avatar answered Dec 22 '22 00:12

Guffa