Trim Tree in C#

Does anyone know if there is a way to trim a tree via C# in Grasshopper? I’m looking to achieve the same as the “trim tree” command.


Yes, Grasshopper is C#, so whatever it can do, you can do. Do note you’ll have a hard time duplicating components that deal with trees using a C# script component, because data is converted before it is handed off to a script component. But if you don’t mind that, then it’s just a matter of iterating over the branches of the old tree and building a new one. I’ll come up with an example. (35.3 KB)

private void RunScript(DataTree<object> T, int K, ref object R)
  DataTree<object> tree = new DataTree<object>();

  for (int i = 0; i < T.BranchCount; i++)
    var path = T.Paths[i];
    var list = T.Branch(i);

    // Limit length of path to a maximum of K elements.
    while (path.Length > K)
      path = path.CullElement();

    tree.AddRange(list, path);

  R = tree;

Hi @DavidRutten, thanks for your response and example. I will give this a try!

This works perfectly, thanks again David!