Create data tree with c#

Hello,

I tried to create a data tree with C# in Grasshopper. Here is my code:

Grasshopper.DataTree<object> tree = new Grasshopper.DataTree<object>();

Rhino.Collections.RhinoList<int> subtree1 = new Rhino.Collections.RhinoList<int>();
Rhino.Collections.RhinoList<int> subtree2 = new Rhino.Collections.RhinoList<int>();

subtree1.Add(10);
subtree2.Add(20);

GH_Path path1 = new GH_Path(1);
GH_Path path2 = new GH_Path(2);

tree.Add(subtree1, path1);
tree.Add(subtree2, path2);

r = tree;

But it doesn’t work. This is what I get:

1 Like

The DataTree.Add() methods adds a single item to the tree. It works in this case because your tree constraint is object. Use AddRange() if you want to add a list of values.

Grasshopper.DataTree<int> tree = new Grasshopper.DataTree<int>();

tree.Add(10, new GH_Path(1));
tree.Add(20, new GH_Path(2));

r = tree;
1 Like

Perfect. It works, here is my code:

 Grasshopper.DataTree<object> tree = new Grasshopper.DataTree<object>();

System.Collections.Generic.List<object> subtree1 = new System.Collections.Generic.List<object>();
System.Collections.Generic.List<object> subtree2 = new System.Collections.Generic.List<object>();

subtree1.Add(10);
subtree2.Add(20);

GH_Path path1 = new GH_Path(1);
GH_Path path2 = new GH_Path(2);

tree.AddRange(subtree1, path1);
tree.AddRange(subtree2, path2);

r = tree;

David, thank you.

1 Like

The code I posted does exactly the same thing, there’s no need for a lot of additional list classes. The DataTree type has its own list management so you can just use Add() and AddRange() directly on it without the need to go through RhinoList<T>.

You are right, but nevertheless good to know that both variations works. Thanks.

@DavidRutten,

Just for information, is it possible to create 3d objects by creating data trees?
So that through the data tree you in fact provide information how these 3d objects are created. Therefore, giving you means to edit their “parents”, respectively them (indirectly).

1 Like

No, the data stored inside the tree is not in any way related to the tree itself. You should think of a data tree as a Dictionary<GH_Path, List<T>>. That’s really all it is plus a bunch of utility functions for flattening and grafting etc.

3 Likes