Exporting with C# Script

Hi all,
Noob to using C# and scripting within grasshopper so I am finding a simple task very difficult to implement. I am trying to create a script that exports already baked geometry by selecting all existing baked geometry in Rhino or selecting by layer. So I know I need to replace the For loop that loops through the items with a “Select All” or “Select by Layer” so to speak but cannot find the correct syntax to make it work.

I am doing this simply because there are some already decent baking components out there and I don’t want to reinvent the wheel.

private void RunScript(DataTree<GeometryBase> geometry, string FileName, string directory, bool export)
  {
    if (export){
      List<Guid> guids = new List<Guid>();
      for (int i = 0; i < geometry.BranchCount; i++){
        for (int n = 0; n < geometry.Branches[i].Count; n++){
          var geom = geometry.Branches[i][n];
          var guid = Rhino.RhinoDoc.ActiveDoc.Objects.Add(geom);
          guids.Add(guid);
        }
      }

      Rhino.RhinoDoc.ActiveDoc.Objects.Select(guids);

      string filepath = Path.Combine(directory, FileName);
      string cmd = "_-Export " + "\"" + filepath + "\"" + " _Enter";

      Rhino.RhinoApp.RunScript(cmd, false);
      Rhino.RhinoDoc.ActiveDoc.Objects.Delete(guids, true);
    }

I’ve tested this previously and it works if I directly input the baked geometry and get its guids. Any help would be much appreciated.
Thanks

Hello
I put the source of my SVG plugin that uses layers for grouping curves.

    //Sort the layer using sortIndex
            SortedDictionary<int, int> sortDictionaryLayer = new SortedDictionary<int, int>();
            for (int i = 0; i < doc.Layers.Count; i++)
            {
                sortDictionaryLayer.Add(doc.Layers[i].SortIndex, i);
            }
            
            //Max layer calculation in order to be able to change order of rendering
            int layer_level = 0;
            int max_level = 0;
            for (int k = 0; k < sortDictionaryLayer.Count; k++)
            {
                layer_level = 0;
                foreach (char c in doc.Layers[sortDictionaryLayer[k]].FullPath)
                {
                    if (c == ':') layer_level++;
                }
                layer_level /= 2;
                if (layer_level > max_level) max_level = layer_level;
            }
            
            for (int k = 0; k < sortDictionaryLayer.Count; k++)
            {
                int layerId = sortDictionaryLayer[k];
                Rhino.DocObjects.RhinoObject[] rhobjs = doc.Objects.FindByLayer(doc.Layers[layerId].Name);

                //Count the level of layer
                layer_level = 0;
                foreach (char c in doc.Layers[layerId].FullPath)
                {
                    if (c == ':') layer_level++;
                }
                layer_level /= 2; ....