Searching for a group guid of a component

Hi,

I would like to ask if there is a better way to find if a current component is inside a group?

I am searching through all objects in the grasshopper document and check a) if object is a group b) if a group contains current component guid. I assume looping can be slow.

Is there a simpler way to do this?

            GH_Document ghdoc = base.OnPingDocument();
            for (int i = 0; i < ghdoc.ObjectCount; i++)
            {
                IGH_DocumentObject obj = ghdoc.Objects[i];
                if (obj.Attributes.DocObject.ToString().Equals("Grasshopper.Kernel.Special.GH_Group"))
                {
                    Grasshopper.Kernel.Special.GH_Group groupp = (Grasshopper.Kernel.Special.GH_Group)obj;
                    if (groupp.ObjectIDs.Contains(this.InstanceGuid))
                        return;
                }

            }

I don’t think it’s too bad to loop through all the components on your canvas. However if you want to run it several times for multiple components it may be worth to have a unique list/hashset of all GUIDs contained in all groups. This way you only loop through your document once and not per component.

You can also speed it up by checking if the types are equal instead of converting type to string first. Strings are heavy weight when looping among many and will put pressure on garbage collection.

obj.Attributes.DocObject.GetType() == typeof(Grasshopper.Kernel.Special.GH_Group)

With LINQ (for me easier to read), something like:

using System.Linq;
return ghdoc.Objects.OfType<GH_Group>().Any(g => g.Contains(this);
// replace this with this.component if scriptcomponent

It does not however catch if your component is part of group A (and not B), but group A is part of group B. For that we need a nested version.

1 Like