Iterate over GH_Structure

Hi,

What is a correct way of iterating over GH_Structure of type GH_String.

I have a bit of code below:

        var x = new GH_Structure<GH_String>();
        DA.GetDataTree(0, out x);
       

        for (int i = 0; i < x.Branches.Count; i++) {

            for (int j = 0; j < x.get_Branch(i).Count; j++) {

                 //I tried this but does not work . How to retrieve a string value here ?
                 string s = x[new GH_Path(i)][j].Value;
            }
    }

Moved to Grasshopper category

Iterate over what? All paths? Branches? Pairs of paths and their associated branches? GH_String instances? Strings? Non-null strings?

First iterate over all branches then over all items in the branches to retrieve string items (not GH_String neither nulls)

The structure isn’t aware of the strings inside GH_String, so that step will have to be in your own code. You can iterate over all non-null values using the AllData(true) method on gh_structure I think.

Can’t tell you much without access to my office computer, which won’t happen till tomorrow.

var tree = default(GH_Structure<GH_String>);

// So it turns out AllData() isn't type-safe... disappointing.
var collection = new List<string>();
foreach (GH_String entry in tree.AllData(true))
  if (entry.Value != null)
    collection.Add(entry.Value);

// Iterate over all paths and branches using a path-index:
collection = new List<string>();
for (int pi = 0; pi < tree.PathCount; pi++)
{
  var path = tree.Paths[pi];
  var list = tree.Branches[pi];
  for (int i = 0; i < list.Count; i++)
    if (list[i] != null)
      if (list[i].Value != null)
        collection.Add(list[i].Value);
}

// Using two foreach loops:
collection = new List<string>();
foreach (var list in tree.Branches)
  foreach (var text in list)
    if (text != null)
      if (text.Value != null)
        collection.Add(text.Value);

// Using a direct item accessor (this is *very* inefficient):
collection = new List<string>();
for (int i = 0; i < tree.DataCount; i++)
{
  var item = tree.get_DataItem(i);
  if (item != null && item.Value != null)
    collection.Add(item.Value);
}

Thanks David Rutten finally I have a good manual how to work with GH_Structure